Click here to Skip to main content
Click here to Skip to main content

Converting a .NET DateTime object to a JavaScript Date object

By , 1 Oct 2012
Rate this:
Please Sign up or sign in to vote.

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:


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:

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.


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

About the Author

Jason N. Gaylord

United States United States
No Biography provided

Comments and Discussions

Suggestionimprovements Pinmembergiammin4-Oct-12 4:43 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 1 Oct 2012
Article Copyright 2012 by Jason N. Gaylord
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid