]> git.ipfire.org Git - thirdparty/moment.git/commitdiff
toISOString returns null for invalid date
authorMaggie Pint <magpint@microsoft.com>
Mon, 9 Jan 2017 04:49:27 +0000 (20:49 -0800)
committerIskren Chernev <iskren.chernev@gmail.com>
Thu, 2 Mar 2017 09:33:17 +0000 (11:33 +0200)
src/lib/moment/format.js
src/test/moment/format.js

index 539f6c8e1a0344330474d14f66862dced1e55759..f6bef415181e6bb286b6a92e200ae50cc6024efd 100644 (file)
@@ -9,18 +9,19 @@ export function toString () {
     return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
 }
 
-export function toISOString () {
+export function toISOString() {
+    if (!this.isValid()) {
+        return null;
+    }
     var m = this.clone().utc();
-    if (0 < m.year() && m.year() <= 9999) {
-        if (isFunction(Date.prototype.toISOString)) {
-            // native implementation is ~50x faster, use it when we can
-            return this.toDate().toISOString();
-        } else {
-            return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
-        }
-    } else {
+    if (m.year() < 0 || m.year() > 9999) {
         return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
     }
+    if (isFunction(Date.prototype.toISOString)) {
+        // native implementation is ~50x faster, use it when we can
+        return this.toDate().toISOString();
+    }
+    return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
 }
 
 /**
index 34ca0e719ffe924a93bfb42f02fdf44b150150f7..10fe7cf0c9f83cb998bdbf14e612881e314f2b34 100644 (file)
@@ -148,6 +148,10 @@ test('toISOString', function (assert) {
     // big negative years
     date = moment.utc('-020123-10-09T20:30:40.678');
     assert.equal(date.toISOString(), '-020123-10-09T20:30:40.678Z', 'ISO8601 format on big negative year');
+
+    //invalid dates
+    date = moment.utc('2017-12-32');
+    assert.equal(date.toISOString(), null, 'An invalid date to iso string is null');
 });
 
 // See https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects