7

C# offers a way to get the current date by DateTime.Now. But the problem is my server is on US and I get the US time when I use DateTime.Now

Is there any way to get the current local time for a specific country in C# as my users are from around the world? (I have locale of each user, so if I Can get the current time for each locale then I’m safe)

I've seen a way using Time Zone but then I have to keep time zone vs country reference.

I’ve searched and most of the question here is about converting UTC time to local time and vice versa. Hope someone would be able to enlighten me.

Community
  • 1
  • 1
Jay Mayu
  • 17,023
  • 32
  • 114
  • 148
  • 1
    I dont offer a solution, but read the blog [Whats wrong with datetime anyway](http://noda-time.blogspot.in/2011/08/what-wrong-with-datetime-anyway.html) for the problems related to DateTime/DateTimeOffet. . – Tilak Jan 10 '13 at 05:47
  • [Get timezone by Country and Region](http://stackoverflow.com/q/7977736) – Karthik T Jan 10 '13 at 05:49
  • 1
    Note that some countries span over several timezones. So knowing only the country may not be enough. Better knowing directly the user timezone from his computer. – Guillaume Jan 10 '13 at 06:19

2 Answers2

5

Save your time in your server using UTC time (DateTime.UtcNow) and then depending on the users time zone you will change this utc time. Never save local time in the db

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
Dan Hunex
  • 5,172
  • 2
  • 27
  • 38
  • Have you read [Whats wrong with datetime anyway](http://noda-time.blogspot.in/2011/08/what-wrong-with-datetime-anyway.html). DateTime + local timezone + Day Light saving is not as simple to solve as it appears – Tilak Jan 10 '13 at 05:51
  • see this post http://stackoverflow.com/questions/8614323/convert-server-utc-time-to-client-local-time – Dan Hunex Jan 10 '13 at 05:54
  • Is it the same as DateTime.Now.ToUniversalTime()? – Edi Wang Jan 10 '13 at 07:14
  • 1
    But how can I get the user time zone? – Joao Leme Jan 25 '13 at 12:42
3

Just look at the TimeZoneInfo class. You should be able to convert to and from local to server time through there while maintaining DST (Daylight Savings time).

DateTimeOffset newTime = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("AppTimeZone"));

You can also find an Open Source Time Zone Implementation by one of the Great Jon Skeet Noda Time

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105