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:
<%: Html.DisplayFor(m=> m.SomeDate.ToLocalTime()) %>
This throws an exception. Can anybody point me in the correct direction on how to convert the UTC date to local datetime for display at customer end. We will be storing dates as UTC and at display time these dates will need to be converted to the local machine equivalent.
To convert the time in any designated time zone to local time, use the TimeZoneInfo. ConvertTime method. The value returned by the conversion is a DateTime whose Kind property always returns Local. Consequently, a valid result is returned even if ToLocalTime is applied repeatedly to the same DateTime.
You can get the time off the server and do this. DateTime myTimeGMT = ServerTime. ToUniversalTime();
DateTime now = DateTime.UtcNow;
DateTime localNow = TimeZoneInfo.ConvertTimeFromUtc(now, TimeZoneInfo.Local);
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With