Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# and Current Local time for different countries

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.

like image 537
Jay Mayu Avatar asked Jan 10 '13 05:01

Jay Mayu


2 Answers

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

like image 138
Dan Hunex Avatar answered Oct 19 '22 18:10

Dan Hunex


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

like image 35
Vishal Suthar Avatar answered Oct 19 '22 17:10

Vishal Suthar