Hi,
My webservice is returning a datetime to a jQuery call. The returned data is
/Date(1245398693390)/
How can I convert this to a javascript friendly date?
Hi,
My webservice is returning a datetime to a jQuery call. The returned data is
/Date(1245398693390)/
How can I convert this to a javascript friendly date?
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 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);
}
}
What is returned is milliseconds since epoch. You could do:
var d = new Date();
d.setTime(1245398693390);
document.write(d);
On how to format the date exactly as you want, see full Date
reference at http://www.w3schools.com/jsref/jsref_obj_date.asp
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));
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:
var d = eval(net_datetime.slice(1, -1)) // convert the string to date correctly
or:
var d = eval("/Date(1245398693390)/".slice(1, -1)) // convert the string to date correctly
To parse the date string using String.replace with backreference:
var milli = "/Date(1245398693390)/".replace(/\/Date\((-?\d+)\)\//, '$1');
var d = new Date(parseInt(milli));