package/.eslintrc000644 0000000206 3560116604 011102 0ustar00000000 000000 { "extends": [ "eslint:recommended" ], "env": { "node": true, "mocha": true }, "plugins": [ "mocha" ] } package/LICENSE000644 0000002067 3560116604 010272 0ustar00000000 000000 The MIT License (MIT) Copyright (c) 2013 Gareth Jones Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package/test/date_format-test.js000644 0000003765 3560116604 014052 0ustar00000000 000000 'use strict'; require('should'); var dateFormat = require('../lib'); function createFixedDate() { return new Date(2010, 0, 11, 14, 31, 30, 5); } describe('date_format', function() { var date = createFixedDate(); it('should default to now when a date is not provided', function() { dateFormat.asString(dateFormat.DATETIME_FORMAT).should.not.be.empty(); }); it('should be usable directly without calling asString', function() { dateFormat(dateFormat.DATETIME_FORMAT, date).should.eql('11 01 2010 14:31:30.005'); }); it('should format a date as string using a pattern', function() { dateFormat.asString(dateFormat.DATETIME_FORMAT, date).should.eql('11 01 2010 14:31:30.005'); }); it('should default to the ISO8601 format', function() { dateFormat.asString(date).should.eql('2010-01-11T14:31:30.005'); }); it('should provide a ISO8601 with timezone offset format', function() { var tzDate = createFixedDate(); tzDate.getTimezoneOffset = function () { return -660; }; // when tz offset is in the pattern, the date should be in local time dateFormat.asString(dateFormat.ISO8601_WITH_TZ_OFFSET_FORMAT, tzDate) .should.eql('2010-01-11T14:31:30.005+1100'); tzDate = createFixedDate(); tzDate.getTimezoneOffset = function () { return 120; }; dateFormat.asString(dateFormat.ISO8601_WITH_TZ_OFFSET_FORMAT, tzDate) .should.eql('2010-01-11T14:31:30.005-0200'); }); it('should provide a just-the-time format', function() { dateFormat.asString(dateFormat.ABSOLUTETIME_FORMAT, date).should.eql('14:31:30.005'); }); it('should provide a custom format', function() { var customDate = createFixedDate(); customDate.getTimezoneOffset = function () { return 120; }; dateFormat.asString('O.SSS.ss.mm.hh.dd.MM.yy', customDate).should.eql('-0200.005.30.31.14.11.01.10'); }); }); package/lib/index.js000644 0000014375 3560116604 011505 0ustar00000000 000000 "use strict"; function padWithZeros(vNumber, width) { var numAsString = vNumber.toString(); while (numAsString.length < width) { numAsString = "0" + numAsString; } return numAsString; } function addZero(vNumber) { return padWithZeros(vNumber, 2); } /** * Formats the TimeOffset * Thanks to http://www.svendtofte.com/code/date_format/ * @private */ function offset(timezoneOffset) { var os = Math.abs(timezoneOffset); var h = String(Math.floor(os / 60)); var m = String(os % 60); if (h.length === 1) { h = "0" + h; } if (m.length === 1) { m = "0" + m; } return timezoneOffset < 0 ? "+" + h + m : "-" + h + m; } function asString(format, date) { if (typeof format !== "string") { date = format; format = module.exports.ISO8601_FORMAT; } if (!date) { date = module.exports.now(); } // Issue # 14 - Per ISO8601 standard, the time string should be local time // with timezone info. // See https://en.wikipedia.org/wiki/ISO_8601 section "Time offsets from UTC" var vDay = addZero(date.getDate()); var vMonth = addZero(date.getMonth() + 1); var vYearLong = addZero(date.getFullYear()); var vYearShort = addZero(vYearLong.substring(2, 4)); var vYear = format.indexOf("yyyy") > -1 ? vYearLong : vYearShort; var vHour = addZero(date.getHours()); var vMinute = addZero(date.getMinutes()); var vSecond = addZero(date.getSeconds()); var vMillisecond = padWithZeros(date.getMilliseconds(), 3); var vTimeZone = offset(date.getTimezoneOffset()); var formatted = format .replace(/dd/g, vDay) .replace(/MM/g, vMonth) .replace(/y{1,4}/g, vYear) .replace(/hh/g, vHour) .replace(/mm/g, vMinute) .replace(/ss/g, vSecond) .replace(/SSS/g, vMillisecond) .replace(/O/g, vTimeZone); return formatted; } function setDatePart(date, part, value, local) { date['set' + (local ? '' : 'UTC') + part](value); } function extractDateParts(pattern, str, missingValuesDate) { // Javascript Date object doesn't support custom timezone. Sets all felds as // GMT based to begin with. If the timezone offset is provided, then adjust // it using provided timezone, otherwise, adjust it with the system timezone. var local = pattern.indexOf('O') < 0; var matchers = [ { pattern: /y{1,4}/, regexp: "\\d{1,4}", fn: function(date, value) { setDatePart(date, 'FullYear', value, local); } }, { pattern: /MM/, regexp: "\\d{1,2}", fn: function(date, value) { setDatePart(date, 'Month', (value - 1), local); } }, { pattern: /dd/, regexp: "\\d{1,2}", fn: function(date, value) { setDatePart(date, 'Date', value, local); } }, { pattern: /hh/, regexp: "\\d{1,2}", fn: function(date, value) { setDatePart(date, 'Hours', value, local); } }, { pattern: /mm/, regexp: "\\d\\d", fn: function(date, value) { setDatePart(date, 'Minutes', value, local); } }, { pattern: /ss/, regexp: "\\d\\d", fn: function(date, value) { setDatePart(date, 'Seconds', value, local); } }, { pattern: /SSS/, regexp: "\\d\\d\\d", fn: function(date, value) { setDatePart(date, 'Milliseconds', value, local); } }, { pattern: /O/, regexp: "[+-]\\d{3,4}|Z", fn: function(date, value) { if (value === "Z") { value = 0; } var offset = Math.abs(value); var timezoneOffset = (value > 0 ? -1 : 1 ) * ((offset % 100) + Math.floor(offset / 100) * 60); // Per ISO8601 standard: UTC = local time - offset // // For example, 2000-01-01T01:00:00-0700 // local time: 2000-01-01T01:00:00 // ==> UTC : 2000-01-01T08:00:00 ( 01 - (-7) = 8 ) // // To make it even more confusing, the date.getTimezoneOffset() is // opposite sign of offset string in the ISO8601 standard. So if offset // is '-0700' the getTimezoneOffset() would be (+)420. The line above // calculates timezoneOffset to matche Javascript's behavior. // // The date/time of the input is actually the local time, so the date // object that was constructed is actually local time even thought the // UTC setters are used. This means the date object's internal UTC // representation was wrong. It needs to be fixed by substracting the // offset (or adding the offset minutes as they are opposite sign). // // Note: the time zone has to be processed after all other fileds are // set. The result would be incorrect if the offset was calculated // first then overriden by the other filed setters. date.setUTCMinutes(date.getUTCMinutes() + timezoneOffset); } } ]; var parsedPattern = matchers.reduce( function(p, m) { if (m.pattern.test(p.regexp)) { m.index = p.regexp.match(m.pattern).index; p.regexp = p.regexp.replace(m.pattern, "(" + m.regexp + ")"); } else { m.index = -1; } return p; }, { regexp: pattern, index: [] } ); var dateFns = matchers.filter(function(m) { return m.index > -1; }); dateFns.sort(function(a, b) { return a.index - b.index; }); var matcher = new RegExp(parsedPattern.regexp); var matches = matcher.exec(str); if (matches) { var date = missingValuesDate || module.exports.now(); dateFns.forEach(function(f, i) { f.fn(date, matches[i + 1]); }); return date; } throw new Error( "String '" + str + "' could not be parsed as '" + pattern + "'" ); } function parse(pattern, str, missingValuesDate) { if (!pattern) { throw new Error("pattern must be supplied"); } return extractDateParts(pattern, str, missingValuesDate); } /** * Used for testing - replace this function with a fixed date. */ function now() { return new Date(); } module.exports = asString; module.exports.asString = asString; module.exports.parse = parse; module.exports.now = now; module.exports.ISO8601_FORMAT = "yyyy-MM-ddThh:mm:ss.SSS"; module.exports.ISO8601_WITH_TZ_OFFSET_FORMAT = "yyyy-MM-ddThh:mm:ss.SSSO"; module.exports.DATETIME_FORMAT = "dd MM yyyy hh:mm:ss.SSS"; module.exports.ABSOLUTETIME_FORMAT = "hh:mm:ss.SSS"; package/test/parse-test.js000644 0000016430 3560116604 012670 0ustar00000000 000000 "use strict"; require("should"); var dateFormat = require("../lib"); describe("dateFormat.parse", function() { it("should require a pattern", function() { (function() { dateFormat.parse(); }.should.throw(/pattern must be supplied/)); (function() { dateFormat.parse(null); }.should.throw(/pattern must be supplied/)); (function() { dateFormat.parse(""); }.should.throw(/pattern must be supplied/)); }); describe("with a pattern that has no replacements", function() { it("should return a new date when the string matches", function() { dateFormat.parse("cheese", "cheese").should.be.a.Date(); }); it("should throw if the string does not match", function() { (function() { dateFormat.parse("cheese", "biscuits"); }.should.throw(/String 'biscuits' could not be parsed as 'cheese'/)); }); }); describe("with a full pattern", function() { var pattern = "yyyy-MM-dd hh:mm:ss.SSSO"; it("should return the correct date if the string matches", function() { var testDate = new Date(); testDate.setUTCFullYear(2018); testDate.setUTCMonth(8); testDate.setUTCDate(13); testDate.setUTCHours(18); testDate.setUTCMinutes(10); testDate.setUTCSeconds(12); testDate.setUTCMilliseconds(392); dateFormat .parse(pattern, "2018-09-14 04:10:12.392+1000") .getTime() .should.eql(testDate.getTime()) ; }); it("should throw if the string does not match", function() { (function() { dateFormat.parse(pattern, "biscuits"); }.should.throw( /String 'biscuits' could not be parsed as 'yyyy-MM-dd hh:mm:ss.SSSO'/ )); }); }); describe("with a partial pattern", function() { var testDate = new Date(); dateFormat.now = function() { return testDate; }; /** * If there's no timezone in the format, then we verify against the local date */ function verifyLocalDate(actual, expected) { actual.getFullYear().should.eql(expected.year || testDate.getFullYear()); actual.getMonth().should.eql(expected.month || testDate.getMonth()); actual.getDate().should.eql(expected.day || testDate.getDate()); actual.getHours().should.eql(expected.hours || testDate.getHours()); actual.getMinutes().should.eql(expected.minutes || testDate.getMinutes()); actual.getSeconds().should.eql(expected.seconds || testDate.getSeconds()); actual .getMilliseconds() .should.eql(expected.milliseconds || testDate.getMilliseconds()); } /** * If a timezone is specified, let's verify against the UTC time it is supposed to be */ function verifyDate(actual, expected) { actual.getUTCFullYear().should.eql(expected.year || testDate.getUTCFullYear()); actual.getUTCMonth().should.eql(expected.month || testDate.getUTCMonth()); actual.getUTCDate().should.eql(expected.day || testDate.getUTCDate()); actual.getUTCHours().should.eql(expected.hours || testDate.getUTCHours()); actual.getUTCMinutes().should.eql(expected.minutes || testDate.getUTCMinutes()); actual.getUTCSeconds().should.eql(expected.seconds || testDate.getUTCSeconds()); actual .getMilliseconds() .should.eql(expected.milliseconds || testDate.getMilliseconds()); } it("should return a date with missing values defaulting to current time", function() { var date = dateFormat.parse("yyyy-MM", "2015-09"); verifyLocalDate(date, { year: 2015, month: 8 }); }); it("should use a passed in date for missing values", function() { var missingValueDate = new Date(2010, 1, 8, 22, 30, 12, 100); var date = dateFormat.parse("yyyy-MM", "2015-09", missingValueDate); verifyLocalDate(date, { year: 2015, month: 8, day: 8, hours: 22, minutes: 30, seconds: 12, milliseconds: 100 }); }); it("should handle variations on the same pattern", function() { var date = dateFormat.parse("MM-yyyy", "09-2015"); verifyLocalDate(date, { year: 2015, month: 8 }); date = dateFormat.parse("yyyy MM", "2015 09"); verifyLocalDate(date, { year: 2015, month: 8 }); date = dateFormat.parse("MM, yyyy.", "09, 2015."); verifyLocalDate(date, { year: 2015, month: 8 }); }); describe("should match all the date parts", function() { it("works with dd", function() { var date = dateFormat.parse("dd", "21"); verifyLocalDate(date, { day: 21 }); }); it("works with hh", function() { var date = dateFormat.parse("hh", "12"); verifyLocalDate(date, { hours: 12 }); }); it("works with mm", function() { var date = dateFormat.parse("mm", "34"); verifyLocalDate(date, { minutes: 34 }); }); it("works with ss", function() { var date = dateFormat.parse("ss", "59"); verifyLocalDate(date, { seconds: 59 }); }); it("works with ss.SSS", function() { var date = dateFormat.parse("ss.SSS", "23.452"); verifyLocalDate(date, { seconds: 23, milliseconds: 452 }); }); it("works with hh:mm O (+1000)", function() { var date = dateFormat.parse("hh:mm O", "05:23 +1000"); verifyDate(date, { hours: 19, minutes: 23 }); }); it("works with hh:mm O (-200)", function() { var date = dateFormat.parse("hh:mm O", "05:23 -200"); verifyDate(date, { hours: 7, minutes: 23 }); }); it("works with hh:mm O (+0930)", function() { var date = dateFormat.parse("hh:mm O", "05:23 +0930"); verifyDate(date, { hours: 19, minutes: 53 }); }); }); }); describe("with a date formatted by this library", function() { describe("should format and then parse back to the same date", function() { function testDateInitWithUTC() { var td = new Date(); td.setUTCFullYear(2018); td.setUTCMonth(8); td.setUTCDate(13); td.setUTCHours(18); td.setUTCMinutes(10); td.setUTCSeconds(12); td.setUTCMilliseconds(392); return td; } it("works with ISO8601_WITH_TZ_OFFSET_FORMAT", function() { // For this test case to work, the date object must be initialized with // UTC timezone var td = testDateInitWithUTC(); var d = dateFormat(dateFormat.ISO8601_WITH_TZ_OFFSET_FORMAT, td); dateFormat.parse(dateFormat.ISO8601_WITH_TZ_OFFSET_FORMAT, d) .should.eql(td); }); it("works with ISO8601_FORMAT", function() { var td = new Date(); var d = dateFormat(dateFormat.ISO8601_FORMAT, td); var actual = dateFormat.parse(dateFormat.ISO8601_FORMAT, d); actual.should.eql(td); }); it("works with DATETIME_FORMAT", function() { var testDate = new Date(); dateFormat .parse( dateFormat.DATETIME_FORMAT, dateFormat(dateFormat.DATETIME_FORMAT, testDate) ) .should.eql(testDate); }); it("works with ABSOLUTETIME_FORMAT", function() { var testDate = new Date(); dateFormat .parse( dateFormat.ABSOLUTETIME_FORMAT, dateFormat(dateFormat.ABSOLUTETIME_FORMAT, testDate) ) .should.eql(testDate); }); }); }); }); package/package.json000644 0000001375 3560116604 011554 0ustar00000000 000000 { "name": "date-format", "version": "3.0.0", "description": "Formatting Date objects as strings since 2013", "main": "lib/index.js", "repository": { "type": "git", "url": "https://github.com/nomiddlename/date-format.git" }, "engines": { "node": ">=4.0" }, "scripts": { "lint": "eslint lib/* test/*", "pretest": "eslint lib/* test/*", "test": "mocha" }, "keywords": [ "date", "format", "string" ], "author": "Gareth Jones ", "license": "MIT", "readmeFilename": "README.md", "gitHead": "bf59015ab6c9e86454b179374f29debbdb403522", "devDependencies": { "eslint": "^5.16.0", "eslint-plugin-mocha": "^5.3.0", "mocha": "^5.2.0", "should": "^13.2.3" } } package/README.md000644 0000003624 3560116604 010544 0ustar00000000 000000 date-format =========== node.js formatting of Date objects as strings. Probably exactly the same as some other library out there. ```sh npm install date-format ``` usage ===== Formatting dates as strings ---- ```javascript var format = require('date-format'); format.asString(); //defaults to ISO8601 format and current date. format.asString(new Date()); //defaults to ISO8601 format format.asString('hh:mm:ss.SSS', new Date()); //just the time ``` or ```javascript var format = require('date-format'); format(); //defaults to ISO8601 format and current date. format(new Date()); format('hh:mm:ss.SSS', new Date()); ``` Format string can be anything, but the following letters will be replaced (and leading zeroes added if necessary): * dd - `date.getDate()` * MM - `date.getMonth() + 1` * yy - `date.getFullYear().toString().substring(2, 4)` * yyyy - `date.getFullYear()` * hh - `date.getHours()` * mm - `date.getMinutes()` * ss - `date.getSeconds()` * SSS - `date.getMilliseconds()` * O - timezone offset in +hm format (note that time will be in UTC if displaying offset) Built-in formats: * `format.ISO8601_FORMAT` - `2017-03-14T14:10:20.391` (local time used) * `format.ISO8601_WITH_TZ_OFFSET_FORMAT` - `2017-03-14T03:10:20.391+1100` (UTC + TZ used) * `format.DATETIME_FORMAT` - `14 03 2017 14:10:20.391` (local time used) * `format.ABSOLUTETIME_FORMAT` - `14:10:20.391` (local time used) Parsing strings as dates ---- The date format library has limited ability to parse strings into dates. It can convert strings created using date format patterns (as above), but if you're looking for anything more sophisticated than that you should probably look for a better library ([momentjs](https://momentjs.com) does pretty much everything). ```javascript var format = require('date-format'); // pass in the format of the string as first argument format.parse(format.ISO8601_FORMAT, '2017-03-14T14:10:20.391'); // returns Date ``` package/.travis.yml000644 0000000100 3560116604 011360 0ustar00000000 000000 language: node_js sudo: false node_js: - "10" - "8" - "6"