Click here to Skip to main content
15,886,797 members
Articles / Programming Languages / XML
Tip/Trick

Converting a .NET DateTime object to a JavaScript Date object

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
1 Oct 2012CPOL 29.7K   5   2
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)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Suggestionimprovements Pin
giammin4-Oct-12 4:43
giammin4-Oct-12 4:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.