7

I have an ASP.NET MVC app. This app uses Razor as the view engine. I need to display a date/time to the user. My challenge is, the DateTime property on the model is in UTC time. I want to display the time as the user's local time. Currently, I have the following:

<div>
@if (Model.LastModifiedOnUTC.HasValue) {
  Html.Raw(Model.LastModifiedOnUTC.ToString());
}
else {
  <span>This record has not been updated</span>
}
</div>

I want to display the DateTime as something like "Wednesday, February 11, 2015 at 3:27 PM". However, I'm not sure how to do this. When I do the above, an empty string is printed. Which doesn't make any sense to me.

Thank you for any insights

user687554
  • 10,663
  • 25
  • 77
  • 138
  • 2
    I believe that this is best done on the client side because the local time zone is known there. So you need to use JavaScript and how is explained in this question: http://stackoverflow.com/questions/6525538/convert-utc-date-time-to-local-date-time-using-javascript – Martin Liversage Feb 11 '15 at 20:40
  • Rick Strahl recently did a blog post about this very topic. One of the items in his post talked about capturing the user's default time zone from the browser and doing the calculation of the correct time server-side. Check out his post at http://weblog.west-wind.com/posts/2015/Feb/10/Back-to-Basics-UTC-and-TimeZones-in-NET-Web-Apps. Scroll down to the section on "Capturing a Web User’s Default Time Zone" – Craig W. Feb 12 '15 at 00:43
  • 1
    Can you unaccept the accepted answer? this is not the correct way to do it because it will retrieve the Servers local time, not the Clients. this can throw off a lot of people. – Jean-Paul Jan 19 '19 at 16:45

2 Answers2

13

One option is to use JavaScript.

in your View

<time>@Model.LastModifiedOnUTC.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture)<time>

JS (my example with JQuery)

$("time").each(function (elem) {
        var utctimeval = $(this).html();
        var date = new Date(utctimeval);
        $(this).html(date.toLocaleString());
})
intox
  • 514
  • 7
  • 14
  • 3
    This code is sensitive to servers culture, sinc the ":" colons could end up as dots. Se [here](https://social.msdn.microsoft.com/Forums/vstudio/en-US/bb926074-d593-4e0b-8754-7026acc607ec/datetime-tostring-colon-replaced-with-period?forum=csharpgeneral). Use instead: – Andriod Jul 29 '18 at 16:24
-12

You can use use following code in razor

<div>
@if (Model.LastModifiedOnUTC.HasValue) {
Html.Raw(Model.LastModifiedOnUTC.ToLocalTime().ToString());
}
else {
<span>This record has not been updated</span>
}
</div>
  • 20
    After deployment of the web site, this ToLocalTime() converts the UTC time to the server time zome and not as per the client browser. – Ashutosh B Bodake Aug 07 '17 at 08:29