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:<
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"))
All good answers. I did mine like this:
@Html.DisplayFor(m=> m.SomeDate.ToLocalTime()
.ToString(
CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern
+ " "
+ CultureInfo.CurrentUICulture.DateTimeFormat.LongTimePattern))
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())
You can't do ToLocalTime() on the server since the server is in UTC. You either need to:
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!
DateTime now = DateTime.UtcNow;
DateTime localNow = TimeZoneInfo.ConvertTimeFromUtc(now, TimeZoneInfo.Local);
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)