get client machine timezone in asp.net mvc

2019-02-07 11:28发布

How to get the time zone id (ex.: Central Standard Time) of the client machine in asp.net mvc?

3条回答
我想做一个坏孩纸
2楼-- · 2019-02-07 11:56

That information is not sent to the server, so there is not trivial way to do it. One option would be to look up the IP in a Geolocation Database. http://www.ip2location.com/ is one.

You can also do a ajax postback using the javascript Date.getTimezoneOffset().

$.get('/User/SetTimeZone' + Date.getTimezoneOffset());

and store this in the session or with the user data.

查看更多
再贱就再见
3楼-- · 2019-02-07 11:56

If you have troubles showing time on the client side then you can do the following I wrote an extension to DateTime class that does conversion for me

public static MvcHtmlString ToClientTime(this DateTime dateTime){
   var builder = new TagBuilder("span");
   builder.MergeAttribute("data-utc-time",dateTime.ToString());
   builder.SetInnerText(string.Format("{0} (UTC)", dateTime.ToString()));
   return new MvcHtmlString(builder.ToString());
}

then I've added a javascript file and let momentjs handle the conversion on the client side

$(document).ready(function() {
  $("[data-utc-time]").text(function () {
    var utcTime = $(this).attr("data-utc-time");
    return moment.utc(utcTime, 'DD.MM.YYYY HH:mm').local().format('DD.MM.YYYY HH:mm');
});
查看更多
聊天终结者
4楼-- · 2019-02-07 11:59

It will have to be done on the Javascript side, and post that value in a hidden field back to the server. Look into the Date.getTimezoneOffset().

查看更多
登录 后发表回答