简体   繁体   中英

How to get the client timezone id for c# timezoneinfo class from client side using javascript

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);'
  1. TimeZoneInfo uses Windows time zone identifiers. They are not going to match anything coming out of JavaScript. Please read the timezone tag wiki .
  2. Identifying the user's time zone in JavaScript is imperfect. You can guess at it, using one of these methods , but that is going to give you an IANA time zone id, not a Windows time zone id.
  3. You can convert IANA time zones to Windows time zones using either my TimeZoneConverter library, or the method described here which uses Noda Time . However if you're going to use Noda Time, you might as well just use IANA time zones in the first place. Noda Time does a much better job than TimeZoneInfo .
  4. If you just want to convert the client's local time to UTC, then just do that in the browser in JavaScript. Then you don't need to know what the local time zone actually is.

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM