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

后端 未结 2 1980
挽巷
挽巷 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.

    0 讨论(0)
  • 2020-12-20 09:06

    Your GetFastestNISTDate function uses the daytime protocol - which is essentially deprecated and NOT meant for machine interaction because its results are in no specific format. Even the docs from NIST strongly encourage users to use NTP instead of daytime.

    You can find a simple C# implementation of an NTP client here.

    To make things easier, I've implemented this client as a NodaTime.IClock. The code is on GitHub here. Simply install it from NuGet:

    Install-Package NodaTime.NetworkClock
    

    Then you can use it just like you would use the SystemClock:

    var instant = NetworkClock.Instance.Now;
    var timeZone = DateTimeZoneProviders.Tzdb["Europe/London"];
    var zonedDateTime = instant.InZone(timeZone);
    
    0 讨论(0)
提交回复
热议问题