Reputation: 201
I want to get client timezone id from JavaScript to parse c# TimezoneInfo class.And Convert to utc time.And I have this
var timezone = String(new Date());
return timezone.substring(timezone.lastIndexOf('(') + 1).replace(')', '').trim();
Problem is some time it will javascript timezone return CST. Is there a proper way to get timezone id
and from the c#
TimeZoneInfo ZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneIdFromJavascript);
return TimeZoneInfo.ConvertTimeToUtc(Datetime, ZoneInfo);'
Upvotes: 13
Views: 8319
Reputation: 93
The safest way I've found is to use only the offset amount from the UTC and not the identifier name.
From Javascript I send this:
var dateString = new Date();
var offset = dateString.getTimezoneOffset();
And on the C# I map this offset to the first Time Zone that has the same offset:
string jsNumberOfMinutesOffset = ViewModel.offset; // sending the above offset
var timeZones = TimeZoneInfo.GetSystemTimeZones();
var numberOfMinutes = Int32.Parse(jsNumberOfMinutesOffset)*(-1);
var timeSpan = TimeSpan.FromMinutes(numberOfMinutes);
var userTimeZone = timeZones.Where(tz => tz.BaseUtcOffset == timeSpan).FirstOrDefault();
This gives us the first timezone which has the same offset received from the client side. Since there are more than one time zones with the same offset it does not always matches the exact time zone of the user but it is completely reliable to convert from UTC to local representation of time.
I'm hoping it helps someone :)
Upvotes: 4
Reputation: 241475
TimeZoneInfo
uses Windows time zone identifiers. They are not going to match anything coming out of JavaScript. Please read the timezone tag wiki.TimeZoneInfo
.Upvotes: 14