Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

Converting a .NET DateTime object to a JavaScript Date object

5.00/5 (1 vote)
1 Oct 2012CPOL 30.4K  
When using a WCF or ASMX web service in ASP.NET, you might find the need to pass back a DateTime object via JSON. However, what you might not realize is that by passing a .NET DateTime object back to JavaScript, you’d receive an “Invalid date” script exception. The data being passe

When using a WCF or ASMX web service in ASP.NET, you might find the need to pass back a DateTime object via JSON. However, what you might not realize is that by passing a .NET DateTime object back to JavaScript, you’d receive an “Invalid date” script exception. The data being passed back to JavaScript may resemble the following:

/Date(1315938182867-0400)/

The reason that the date is formatted in this way is that JavaScript uses Unix Epoch as the base date and time. This value is 1/1/1970 at 12:00:00 AM. JavaScript tracks dates as the number of milliseconds from the Unix Epoch value to the date submitted.

To assist in the JavaScript date conversion, I have added an extension method for the DateTime object that resembles the following:

C#
private static readonly long UnixEpochTicks = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks; 
        
public static long? ToJsonTicks(this DateTime? value)
{
    return value == null ? (long?)null : (value.Value.ToUniversalTime().Ticks - UnixEpochTicks) / 10000;
}

public static long ToJsonTicks(this DateTime value)
{
    return (value.ToUniversalTime().Ticks - UnixEpochTicks) / 10000;
}

In JavaScript, I can now pass this value into a Date() object and get the correct DateTime value for my locale.

Feel free to use this method in your applications. I offer no warranties or guarantees with the code above.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)