get client machine timezone in asp.net mvc

后端 未结 3 1955
旧巷少年郎
旧巷少年郎 2021-01-01 06:59

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

3条回答
  •  青春惊慌失措
    2021-01-01 07:33

    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');
    });
    

提交回复
热议问题