From: Oliver, Jonathan Date: Thu, 29 Dec 2011 05:08:09 +0000 (-0700) Subject: Added tests and behavior to accept JSON-encoded date values. X-Git-Tag: 1.4.0~31^2~1 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=cd415b734e2baa8e968f441c809fc420fa44f3a6;p=thirdparty%2Fmoment.git Added tests and behavior to accept JSON-encoded date values. For more information, see http://blog.activa.be/index.php/2010/03/handling-dates-in-json-responses-with-jquery-1-4-the-easy-way/ --- diff --git a/moment.js b/moment.js index 4167f7270..fa322a71e 100644 --- a/moment.js +++ b/moment.js @@ -13,6 +13,7 @@ hasModule = (typeof module !== 'undefined'), paramsToParse = 'months|monthsShort|monthsParse|weekdays|weekdaysShort|longDateFormat|calendar|relativeTime|ordinal|meridiem'.split('|'), i, + jsonRegex = /\/?Date\((\d+)((?:\-|\+)\d+)?\)\/?/i, charactersToReplace = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|dddd?|do?|w[o|w]?|YYYY|YY|a|A|hh?|HH?|mm?|ss?|zz?|ZZ?|LT|LL?L?L?)/g, nonuppercaseLetters = /[^A-Z]/g, timezoneRegex = /\([A-Za-z ]+\)|:[0-9]{2} [A-Z]{3} /g, @@ -358,7 +359,7 @@ if (input === null) { return null; } - var date; + var date, matched; // parse UnderscoreDate object if (input && input._d instanceof Date) { date = new Date(+input._d); @@ -369,6 +370,9 @@ } else { date = makeDateFromStringAndFormat(input, format); } + // evaluate it as a JSON-encoded date + } else if (matched = jsonRegex.exec(input)) { + date = new Date(parseInt(matched[1])); // parse everything else } else { date = input === undefined ? new Date() : diff --git a/sitesrc/js/unit-tests.js b/sitesrc/js/unit-tests.js index 8f76abacb..43c91c357 100755 --- a/sitesrc/js/unit-tests.js +++ b/sitesrc/js/unit-tests.js @@ -57,6 +57,12 @@ test("string without format", 2, function() { ok(moment("Mon, 25 Dec 1995 13:30:00 GMT").native() instanceof Date, "Mon, 25 Dec 1995 13:30:00 GMT"); }); +test("string without format - json", 4, function() { + ok(moment("Date(1325132654000)").valueOf() === 1325132654000, "Date(1325132654000)"); + ok(moment("/Date(1325132654000)/").valueOf() === 1325132654000, "/Date(1325132654000)/"); + ok(moment("/Date(1325132654000+0700)/").valueOf() === 1325132654000, "/Date(1325132654000+0700)/"); + ok(moment("/Date(1325132654000-0700)/").valueOf() === 1325132654000, "/Date(1325132654000-0700)/"); +}); test("string with format", 18, function() { moment.lang('en');