Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC - UTC date to LocalTime

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.

like image 760
Amitesh Avatar asked May 11 '11 02:05

Amitesh


People also ask

How to convert the DateTime to LocalTime?

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.

How to convert server time to local time in c#?

You can get the time off the server and do this. DateTime myTimeGMT = ServerTime. ToUniversalTime();


2 Answers

DateTime now = DateTime.UtcNow;
DateTime localNow = TimeZoneInfo.ConvertTimeFromUtc(now, TimeZoneInfo.Local);
like image 194
Chad Moran Avatar answered Sep 16 '22 17:09

Chad Moran


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"))
like image 29
Trent Scholl Avatar answered Sep 19 '22 17:09

Trent Scholl