Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Controller/View display local time

I have an ASP.NET MVC app that stores all SQL DateTime in UTC, so that the time is consistent regardless of time zone that the client is hitting the site from.

Now, I want to re-display the correct time to the user, so any time I display a time in my View I use:

timeVariable.ToLocalTime();

However, .ToLocalTime() is based on the server, not the client.

Do I need to handle this in JavaScript on the client?

I probably could pass the time zone as part of the request and have the controller handle the offest, but I am assuming there is a better way to do this. Or isn't there?

Thanks in advance for any help!

-Matt

like image 963
MattW Avatar asked Nov 15 '11 22:11

MattW


People also ask

How to get Date Time in MVC?

var userDt = DateTime. Now. ToString("MM/dd/yyyy hh:mm tt"); // return 08/05/2016 12:56 PM.

How to convert DateTime in MVC?

var date = DateTime. Parse(model. dateValue); var printInfo = string. Format("{0:MM/dd/yyyy HH:mm:ss}", date);

How to add DateTime in MVC?

You can create a new DateTime as follow: var myDate = new DateTime(2014, 2, 19); Also see the MSDN on http://msdn.microsoft.com/en-us/library/xcfzdy4x(v=vs.110).aspx.


1 Answers

For Asp.Net MVC + jQuery I've created a DisplayTemplate and script to help with this.

Model class:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

public class SampleModelWithDate
{
    [UIHint("UTCTime")]
    [DataType(DataType.DateTime)]
    public DateTime Date { get; set; }
}

DisplayTemplate: Views\Shared\DisplayTemplates\UTCTime.cshtml

@model DateTime
<span class="UTCTime">@Model</span>

Add to Views\Shared_Layout.cshtml, or to your View:

<script>
    $(function () {
        // Determine timezone offset in milliseconds
        // from: http://www.w3schools.com/jsref/jsref_getTimezoneOffset.asp
        var d = new Date()
        var offsetms = d.getTimezoneOffset() * 60 * 1000;
        $('.UTCTime').each(function () {
            try
            {
                var text = $(this).html();

                var n = new Date(text);
                n = new Date(n.valueOf() - offsetms);

                $(this).html(n.toDateString() + " " + n.toLocaleTimeString());

                $(this).attr("Converted from UTC " + text);
            }
            catch (ex) {
                console.warn("Error converting time", ex);
            }
        });
    });
</script>

Clean it up a little of course, it's a bit verbose so you can see what's going on.

like image 70
Derrick Avatar answered Oct 21 '22 13:10

Derrick