How Convert UTC Date & time to local time using different timezone Nodatime

后端 未结 2 1982
挽巷
挽巷 2020-12-20 08:29

i am using a function which is taking date time over the internet from external server. here is the function which i am using to get date and time without depend on user pc

2条回答
  •  甜味超标
    2020-12-20 08:43

    You shouldn't be converting the DateTime to a string and back - but your current problem is that you're converting the UTC value you get back from the server into a local DateTime for no obvious reason. Ideally, I'd suggest changing GetFastestNISTDate() to return an Instant, but assuming you can't do that:

    • Don't do the parsing yourself. Take the appropriate substring from the response, then use DateTime.ParseExact, specifying CultureInfo.InvariantCulture and DateTimeStyles.AssumeUniversal
    • Don't convert the UTC DateTime to a local version - it's pointless and confusing
    • Use Instant.FromDateTimeUtc to convert a UTC DateTime to an instant

    The final part of your code (the last three lines) is okay, but why do you need a DateTime at all? If you can make as much of your code as possible use Noda Time, you'll get the greatest benefits in terms of code clarity.

提交回复
热议问题