From 322339876e751abc6f5cb32aeea94d6afd628085 Mon Sep 17 00:00:00 2001 From: Dan Stillman Date: Wed, 29 Apr 2015 17:26:05 -0400 Subject: [PATCH] Add Zotero.Date.isISODate() and Zotero.Date.isoToSQL() --- chrome/content/zotero/xpcom/date.js | 17 +++++++++++++++-- test/tests/dateTest.js | 11 +++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 test/tests/dateTest.js diff --git a/chrome/content/zotero/xpcom/date.js b/chrome/content/zotero/xpcom/date.js index c41b5eec50..a4ca171e3c 100644 --- a/chrome/content/zotero/xpcom/date.js +++ b/chrome/content/zotero/xpcom/date.js @@ -180,6 +180,15 @@ Zotero.Date = new function(){ } + var _re8601 = /^([0-9]{4})(-([0-9]{2})(-([0-9]{2})(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?$/; + + /** + * @return {Boolean} - True if string is an ISO 8601 date, false if not + */ + this.isISODate = function (str) { + return _re8601.test(str); + } + /** * Convert an ISO 8601–formatted UTC date/time to a JS Date * @@ -189,8 +198,7 @@ Zotero.Date = new function(){ * @return {Date} JS Date */ this.isoToDate = function (isoDate) { - var re8601 = /([0-9]{4})(-([0-9]{2})(-([0-9]{2})(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?/; - var d = isoDate.match(re8601); + var d = isoDate.match(_re8601); var offset = 0; var date = new Date(d[1], 0, 1); @@ -212,6 +220,11 @@ Zotero.Date = new function(){ } + this.isoToSQL = function (isoDate) { + return this.dateToSQL(this.isoToDate(isoDate), true); + } + + /* * converts a string to an object containing: * day: integer form of the day diff --git a/test/tests/dateTest.js b/test/tests/dateTest.js new file mode 100644 index 0000000000..dd6d6ff60c --- /dev/null +++ b/test/tests/dateTest.js @@ -0,0 +1,11 @@ +describe("Zotero.Date", function() { + describe("#isISODate()", function () { + it("should determine whether a date is an ISO 8601 date", function () { + assert.ok(Zotero.Date.isISODate("2015")); + assert.ok(Zotero.Date.isISODate("2015-04")); + assert.ok(Zotero.Date.isISODate("2015-04-29")); + assert.ok(Zotero.Date.isISODate("2015-04-29T17:28Z")); + assert.isFalse(Zotero.Date.isISODate("2015-04-29 17:28")); + }) + }) +})