From: Isaac Cambron Date: Sat, 7 Sep 2013 22:44:29 +0000 (-0400) Subject: create moments with objects X-Git-Tag: 2.2.0~6^2~1^2~1 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=f09f73dc7352258511893aeaf6c450e898d4d0bb;p=thirdparty%2Fmoment.git create moments with objects --- diff --git a/moment.js b/moment.js index 03d66a4e0..39b08ea43 100644 --- a/moment.js +++ b/moment.js @@ -841,6 +841,26 @@ config._d = date; } + function dateFromObject(config) { + var o = config._i; + + if (config._d) { + return; + } + + config._a = [ + o.years || o.year || o.y, + o.months || o.month || o.m, + o.days || o.day || o.d, + o.hours || o.hour || o.h, + o.minutes || o.minute || o.m, + o.seconds || o.second || o.s, + o.milliseconds || o.millisecond || o.ms + ]; + + dateFromArray(config); + } + function currentDateArray(config) { var now = new Date(); if (config._useUTC) { @@ -963,8 +983,12 @@ } else if (isArray(input)) { config._a = input.slice(0); dateFromArray(config); + } else if (input instanceof Date) { + config._d = new Date(+input); + } else if (typeof(input) == 'object') { + dateFromObject(config); } else { - config._d = input instanceof Date ? new Date(+input) : new Date(input); + config._d = new Date(input); } } diff --git a/test/moment/create.js b/test/moment/create.js index 634b4514f..61928264d 100644 --- a/test/moment/create.js +++ b/test/moment/create.js @@ -22,6 +22,19 @@ exports.create = { test.done(); }, + "object" : function (test) { + test.expect(8); + test.ok(moment({year: 2010}).toDate() instanceof Date, "{year: 2010}"); + test.ok(moment({year: 2010, month: 1}).toDate() instanceof Date, "{year: 2010, month: 1}"); + test.ok(moment({year: 2010, month: 1, day: 12}).toDate() instanceof Date, "{year: 2010, month: 1, day: 12}"); + test.ok(moment({year: 2010, month: 1, day: 12, hours: 1}).toDate() instanceof Date, "{year: 2010, month: 1, day: 12, hours: 1}"); + test.ok(moment({year: 2010, month: 1, day: 12, hours: 1, minutes: 1}).toDate() instanceof Date, "{year: 2010, month: 1, hours: 12, minutes: 1, seconds: 1}"); + test.ok(moment({year: 2010, month: 1, day: 12, hours: 1, minutes: 1, seconds: 1}).toDate() instanceof Date, "{year: 2010, month: 1, day: 12, hours: 1, minutes: 1, seconds: 1]"); + test.ok(moment({year: 2010, month: 1, day: 12, hours: 1, minutes: 1, seconds: 1, milliseconds: 1}).toDate() instanceof Date, "{year: 2010, month: 1, day: 12, hours: 1, minutes: 1, seconds: 1, milliseconds: 1]"); + test.equal(+moment(new Date(2010, 1, 14, 15, 25, 50, 125)), +moment({year: 2010, month: 1, day: 14, hours: 15, minutes: 25, seconds: 50, milliseconds: 125}), "constructing with object === constructing with new Date()"); + test.done(); + }, + "multi format array copying": function (test) { var importantArray = ['MM/DD/YYYY', 'YYYY-MM-DD', 'MM-DD-YYYY']; test.expect(1);