MVC - UTC date to LocalTime

前端 未结 9 466
春和景丽
春和景丽 2020-12-28 10:07

We have a MVC project and I need to display a UTC date converted to users local time. In my model I am passing the UTC date and in the view I am trying to do the following:<

相关标签:
9条回答
  • 2020-12-28 10:37

    You will need to store the users timezone server side and then use something like this (although it should be done in the controller, not the view):

    @TimeZoneInfo.ConvertTimeFromUtc(Model.CreatedOn, TimeZoneInfo.FindSystemTimeZoneById("E. Australia Standard Time"))
    
    0 讨论(0)
  • 2020-12-28 10:38

    All good answers. I did mine like this:

    @Html.DisplayFor(m=> m.SomeDate.ToLocalTime()
        .ToString(
            CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern 
            + " " 
            + CultureInfo.CurrentUICulture.DateTimeFormat.LongTimePattern))
    
    0 讨论(0)
  • 2020-12-28 10:40

    Use this code to convert utc time to local time

    <%: Html.DisplayFor(m=> m.SomeDate.ToLocalTime().ToString()) %>
    

    You can use use following code in razor

    @Html.DisplayFor(m=> m.SomeDate.ToLocalTime().ToString())
    
    0 讨论(0)
  • 2020-12-28 10:41

    You can't do ToLocalTime() on the server since the server is in UTC. You either need to:

    1. Have the client somehow send up it's timezone (this can be tricky since you won't get it by default with a GET request)
    2. Have the server send down UTC and the client converts it to the local time. This happens naturally if you're using AJAX, but is cumbersome with just a razor view:

    Here's a trick I used for to make the 2nd approach very easy for Razor views:

    The server renders elements with a special class ".mytime" and the utc time (from server) specified in a custom attribute "utc":

       <div class="mytime" utc ="@date.ToString("o")"></div>
       <span class="mytime" utc ="2018-12-28T02:36:13.6774675Z"></span>
    

    Note that .ToString("o") is how to write in UTC time.

    And then have a local jQuery function iterate through all the elements with "mytime" class, read the UTC value in the attribute, and then do the conversion.

    $(function () {
        var key = $(".mytime").each(function (i, obj) {
            var element = $(this); // <div> or <span> element. 
            var utc = element.attr("utc"); // "2018-12-28T02:36:13.6774675Z"
            var d = new Date(utc);
            var l = d.toLocaleString(); // Runs client side, so will be client's local time!
            element.text(l);
        });
    });
    

    I then created a MVC razor helper for rendering:

    public static MvcHtmlString LocalDate(this HtmlHelper helper, DateTime date)
    {
        // Must use MvcHtmlString to avoid encoding.
        return new MvcHtmlString(String.Format("<span class=\"mytime\" utc =\"{0}\"></span>", date.ToString("o")));
    }
    

    So now my view just includes JQuery and script above and then does:

    Created at @Html.LocalDate(Model.CreatedDate)
    

    Since this is invoked in jQuery's $() onload, it runs after the server has sent down all the times.

    Worked like a charm!

    0 讨论(0)
  • 2020-12-28 10:50
    DateTime now = DateTime.UtcNow;
    DateTime localNow = TimeZoneInfo.ConvertTimeFromUtc(now, TimeZoneInfo.Local);
    
    0 讨论(0)
  • 2020-12-28 10:56

    In a .NET Core project, I finally had success with the following razor code:

    @Model.DateUpdated.ToLocalTime().ToString(
                      CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern 
                      + " " + 
                      CultureInfo.CurrentUICulture.DateTimeFormat.LongTimePattern)
    

    (Inspiration taken from Kelly R's answer)

    0 讨论(0)
提交回复
热议问题