0

I like to save the current DateTime.Now for the current user as UTC. For any user the time is than relative to each other ? I used this code snippet to realize UTC for the Entity Framework: Entity Framework DateTime and UTC

After a look into the database the column for the date has not changed.

09.05.2014 20:21:24

I need to show on the client side the date relative to each user. So when the user created his account in America 14:00 I like to see in Europe 20:00.

Community
  • 1
  • 1
MR.ABC
  • 4,712
  • 13
  • 44
  • 88
  • 1
    Get the DateTime column value then do a `.ToLocal()` – T McKeown May 09 '14 at 18:37
  • You mean on the client side ? – MR.ABC May 09 '14 at 18:38
  • 2
    yes, in an environment that is set to the localtime. If it is variable then you would need to convert it to that specific timezone manually. The important thing is to save the DateTime in UTC. – T McKeown May 09 '14 at 18:39
  • Seems like it does not saved as UTC. Even with the DateTimeKind Attribute. – MR.ABC May 09 '14 at 18:42
  • Is the the type of the column a datime or are you just saving strings? – Rand Random May 09 '14 at 18:51
  • Even if the datetime is in UTC, it is [impractical](http://blogs.msdn.com/b/bartd/archive/2009/03/31/the-death-of-datetime.aspx) to convert historical DateTime values to/from time zones, specially those that has Daylight Savings Time. – thepirat000 May 09 '14 at 18:52
  • 1
    UTC is the Greenwich time then it in Europe so it's normal to see it 20 instead of 14 – Wahid Bitar May 09 '14 at 19:33

2 Answers2

1

Calling .ToLocalTime() on a DateTime object will convert it to the local time. You should always Save the date as UTC then convert upon display.

T McKeown
  • 12,971
  • 1
  • 25
  • 32
  • Why i see the string like 09.05.2014 20:21:24 in the database. Is it already UTC ? I dont think so. So the DateTimeKind Attribute is not workin. – MR.ABC May 09 '14 at 18:42
  • how are you setting the DateTime? `.ToUniversalTime()` – T McKeown May 09 '14 at 18:45
1

First of all you need to use DateTime.UtcNow instead of DateTime.Now. EF will save date as it is, it will not do anything.

For database, it is just a date, whether it is UTC or specific time zone, database has no idea. It is only when we retrieve date from database, before displaying it to local user, we should call ToLocalTime or similar method in client UI library to convert UTC into localtime. ToLocalTime assumes that input is actually UTC.

If you are saving date from client side, for example with AJAX post in JavaScript, JavaScript dates should be serialized as UTC.

Remember that server has no idea from where you are sending date, server cannot convert any date to UTC, client on other hand has complete idea of which country and which timezone it is set at and it can easily convert local time into UTC.

Akash Kava
  • 39,066
  • 20
  • 121
  • 167