How to format this:
/Date(1292962456255)/
as regular looking date in JavaScript/jQuery?
-
What kind of a date is this? A timestamp?Pekka– Pekka2010年12月21日 20:19:44 +00:00Commented Dec 21, 2010 at 20:19
-
Comes back to Json like this from a c3 Datetime objectslandau– slandau2010年12月21日 20:20:41 +00:00Commented Dec 21, 2010 at 20:20
-
2what exactly is the expected output of this date?KJYe.Name– KJYe.Name2010年12月21日 20:20:54 +00:00Commented Dec 21, 2010 at 20:20
-
I really don't know. For some reason passing a c# datetime through json to the view comes back like this after I perform a .toString() on itslandau– slandau2010年12月21日 20:22:28 +00:00Commented Dec 21, 2010 at 20:22
-
@John -- maybe? i really dont knowslandau– slandau2010年12月21日 20:23:14 +00:00Commented Dec 21, 2010 at 20:23
4 Answers 4
This is what I call an "Microsoft Date" and the following function will convert the encoded date to a javascript date time
var msDateToJSDate = function(msDate) {
var dtE = /^\/Date\((-?[0-9]+)\)\/$/.exec(msDate);
if (dtE) {
var dt = new Date(parseInt(dtE[1], 10));
return dt;
}
return null;
}
5 Comments
return msEncodedDate? If the string doesn't match the pattern, return the function itself? That doesn't make any sense at all.Check out moment.js! It's "A lightweight javascript date library for parsing, manipulating, and formatting dates". It is a really powerful little library.
Here's an example...
var today = moment(new Date());
today.format("MMMM D, YYYY h:m A"); // outputs "April 11, 2012 2:32 PM"
// in one line...
moment().format("MMMM D, YYYY h:m A"); // outputs "April 11, 2012 2:32 PM"
Here's another example...
var a = moment([2012, 2, 12, 15, 25, 50, 125]);
a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, March 12th 2012, 3:25:50 pm"
a.format("ddd, hA"); // "Mon, 3PM"
a.format("D/M/YYYY"); // "12/3/2012"
Also, its worth mentioning to checkout date.js. I think the two libraries complement each other.
Comments
The number is a timestamp with millisecond resolution. This number can be passed to JavaScript's Date class' constructor. All that is needed is some code to extract it from the string:
var dateString = "/Date(1292962456255)/";
var matches = dateString.match(/^\/Date\((\d+)\)\/$/);
var date = new Date(parseInt(matches[1], 10));
The regexp on the second line gets a bit messy since the string contains /, ( and ) at precisely the positions that they are needed in the regexp (are you sure what you have is strings that look like that, and not a description of a pattern that would extract them?).
Another way of doing it is to use eval:
var dateString = "/Date(1292962456255)/";
var date = eval("new " + dateString.substring(1, dateString.length - 1));
but that may open up for an XSS attack, so I don't recommend it.
3 Comments
I think this a microtime. Similar to PHP's microtime function. Or in new Date().getTime() in JavaScript.
// PHP
$ php -r "var_dump(microtime(true));"
float(1292963152.1249)
// JavaScript
new Date().getTime()
1292963411830