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
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:
DateTime.ParseExact
, specifying CultureInfo.InvariantCulture
and DateTimeStyles.AssumeUniversal
DateTime
to a local version - it's pointless and confusingInstant.FromDateTimeUtc
to convert a UTC DateTime
to an instantThe 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.
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);