Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Local Date/Time in ASP.NET MVC Razor View

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

like image 963
user687554 Avatar asked Feb 11 '15 20:02

user687554


1 Answers

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());
})
like image 174
intox Avatar answered Nov 12 '22 20:11

intox