Lara
Lara

Reputation: 3021

Convert UTC DateTime from server to Local DateTime on web page

I have a DateTime column field in Sql which is storing Values as UTC. Now I have a requirement where in my reports I have to convert the UTC into Local Time as per the geographical location from where User is accessing the report.

Now I know that ToLocalTime() will convert it into required but at the same time it will convert to the place where application is deployed i.e Server not the User's Geo location .

Here is my code snippet ..

<td>@string.Format("{0:yyyy-MMM-dd HH:mm:ss}", user.StatusDateTime.ToLocalTime())</td>

I am using Razor View and javascript/jquery in User interface.
What would be the possible solution ?

Upvotes: 1

Views: 1315

Answers (1)

Arghya C
Arghya C

Reputation: 10078

Okay, what you can do is, pass the date to the view (without .ToLocalTime()), and then use JavaScript to render local date as shown in the link.

<script>document.write(new Date('@user.StatusDateTime.ToString("yyyy-MM-dd hh:mm:ss UTC")').toString());</script>

Notice the .ToString("yyyy-MM-dd hh:mm:ss UTC") to satisfy JavaScript (I guess there are better ways).

Edit

If you want to show the date in some specific format (e.g. 2015-Dec-22 12:11:38), you can use a custom JavaScript function. Here is an example.

function getFormattedLocalDate(utcDateString) {
    var date = new Date(utcDateString);
    var months = [
      "Jan", "Feb", "Mar", "Apr", "May", "Jun", 
      "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    ];
    var formattedDate = date.getFullYear() + '-' + months[date.getMonth()] + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
    return formattedDate;
}

See it live.

Edit 2

Sample use inside html table here.

Upvotes: 1

Related Questions