Converting a .NET DateTime object to a JavaScript Date object

Posted by: Jason N. Gaylords Blog, on 28 Sep 2011 | View original | Bookmarked: 0 time(s)

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, youd 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:

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.

Category: JavaScript | Other Posts: View all posts by this blogger | Report as irrelevant | View bloggers stats | Views: 1136 | Hits: 21

Similar Posts

  • SQL SERVER Denali Date and Time Functions DATEFROMPARTS() DATETIMEFROMPARTS() DATETIME2FROMPARTS() TIMEFROMPARTS() SMALLDATETIMEFROMPARTS() DATETIMEOFFSETFROMPARTS() A Quick Introduction more
  • Introducing Recurring Appointments for Web.UI Scheduler ASP.NET AJAX more
  • Eschewing Date Types in our Database more
  • LINQ Tip of the week: System.DateTime support more
  • CodeDigest.Com - Articles,FAQs, Codes, News - Aug,2009 more
  • Using the ObjectContainer in disconnected scenarios Part 2 more
  • AJAX Logging with Exponential Backoff more
  • A Lightweight Event Framework in JavaScript more
  • Exposing Custom WCF Headers through WCF Behaviors - Part 2 more
  • Eloquera Database - the web-oriented client/server object database for .NET more

News Categories

.NET | Agile | Ajax | Architecture | ASP.NET | BizTalk | C# | Certification | Data | DataGrid | DataSet | Debugger | DotNetNuke | Events | GridView | IIS | Indigo | JavaScript | Mobile | Mono | Patterns and Practices | Performance | Podcast | Refactor | Regex | Security | Sharepoint | Silverlight | Smart Client Applications | Software | SQL | VB.NET | Visual Studio | W3 | WCF | WinFx | WPF | WSE | XAML | XLinq | XML | XSD