Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Now giving incorrect time

I'm developing an application in Visual Studio using C#. When I create a new instance of an object I want to attach the current date and time to it. Using DateTime.Now the time is off by one hour.

I presume its a time-zone or daylight saving issue. I tried calling System.Globalization.CultureInfo.CurrentCulture.ClearCachedData() right before DateTime.Now but got the same result. How do I resolve this?

like image 948
Paulie22 Avatar asked May 17 '14 14:05

Paulie22


People also ask

How accurate is DateTime now?

Now has an approximate resolution of 10 milliseconds on all NT operating systems. The actual precision is hardware dependent.

What timezone does DateTime now return?

Now and Culture/Timezone specific and C#: Making sure DateTime. Now returns a GMT + 1 time which seem relevant, but no pointers as to the cause of "DateTime. Now not corresponding to machine settings".

Why use DateTimeOffset?

DateTime values lack any knowledge of time zone, or lack thereof. If you need to know when things actually occurred, with more precision than just the approximate date, and you can't be 100% sure that your dates are ALWAYS stored in UTC, then you should consider using DateTimeOffset to represent your datetime values.

What is the difference between DateTime now and DateTime UtcNow?

UtcNow tells you the date and time as it would be in Coordinated Universal Time, which is also called the Greenwich Mean Time time zone - basically like it would be if you were in London England, but not during the summer. DateTime. Now gives the date and time as it would appear to someone in your current locale.


1 Answers

You should use DateTime.UtcNow instead of DateTime.Now to avoid time zone issues (DateTime.Now uses the time zone of the server), then you can convert the UTC value to the user's time zone.

like image 52
gbellmann Avatar answered Sep 22 '22 01:09

gbellmann