[javascript] Converting .NET DateTime to JSON

Possible Duplicate:
How to format a JSON date?

My webs service is returning a DateTime to a jQuery call. The service returns the data in this format:

/Date(1245398693390)/

How can I convert this into a JavaScript-friendly date?

This question is related to javascript json datetime

The answer is


http://stevenlevithan.com/assets/misc/date.format.js

var date = eval(data.Data.Entity.Slrq.replace(/\/Date\((\d )\)\//gi, "new Date($1)"));  
alert(date.format("yyyy-MM-dd HH:mm:ss"));  
alert(dateFormat(date, "yyyy-MM-dd HH:mm:ss"));  

To parse the date string using String.replace with backreference:

var milli = "/Date(1245398693390)/".replace(/\/Date\((-?\d+)\)\//, '$1');
var d = new Date(parseInt(milli));

The previous answers all state that you can do the following:

var d = eval(net_datetime.slice(1, -1));

However, this doesn't work in either Chrome or FF because what's getting evaluated literally is:

// returns the current timestamp instead of the specified epoch timestamp
var d = Date([epoch timestamp]);

The correct way to do this is:

var d = eval("new " + net_datetime.slice(1, -1)); // which parses to

var d = new Date([epoch timestamp]); 

You can try a 3rd party library like json.net There's documention on the project site. It does say it requires .net 3.5.

Otherwise there's another one called Nii.json which i believe is a port from java. I found a link to it on this blog


I have been using this method for a while:

using System;

public static class ExtensionMethods {
  // returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)
  public static double UnixTicks(this DateTime dt)
  {
    DateTime d1 = new DateTime(1970, 1, 1);
    DateTime d2 = dt.ToUniversalTime();
    TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
    return ts.TotalMilliseconds;
  }
}

Assuming you are developing against .NET 3.5, it's a straight copy/paste. You can otherwise port it.

You can encapsulate this in a JSON object, or simply write it to the response stream.

On the Javascript/JSON side, you convert this to a date by simply passing the ticks into a new Date object:

jQuery.ajax({
  ...
  success: function(msg) {
    var d = new Date(msg);
  }
}

If you're having trouble getting to the time information, you can try something like this:

    d.date = d.date.replace('/Date(', '');
    d.date = d.date.replace(')/', '');  
    var expDate = new Date(parseInt(d.date));

the conversion from 1970,1,1 needs the double rounded to zero decimal places i thinks

DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = dt.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return Math.Round( ts.TotalMilliseconds,0);

on the client side i use

new Date(+data.replace(/\D/g, ''));

Thought i'd add my solution that i've been using.

If you're using the System.Web.Script.Serialization.JavaScriptSerializer() then the time returned isn't going to be specific to your timezone. To fix this you'll also want to use dte.getTimezoneOffset() to get it back to your correct time.

String.prototype.toDateFromAspNet = function() {
    var dte = eval("new " + this.replace(/\//g, '') + ";");
    dte.setMinutes(dte.getMinutes() - dte.getTimezoneOffset());
    return dte;
}

now you'll just call

"/Date(1245398693390)/".toDateFromAspNet();

Fri Jun 19 2009 00:04:53 GMT-0400 (Eastern Daylight Time) {}


If you pass a DateTime from a .Net code to a javascript code, C#:

DateTime net_datetime = DateTime.Now;

javascript treats it as a string, like "/Date(1245398693390)/":

You can convert it as fllowing:

// convert the string to date correctly
var d = eval(net_datetime.slice(1, -1))

or:

// convert the string to date correctly
var d = eval("/Date(1245398693390)/".slice(1, -1))

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?