UNPKG

@head.js/analytics.js-new-date

Version:

Creates a new Date, but accepts a few more input types than normal.

53 lines (44 loc) 1.18 kB
"use strict"; var isodate = require("@segment/isodate"); var milliseconds = require("./milliseconds"); var seconds = require("./seconds"); var objProto = Object.prototype; var toStr = objProto.toString; function isDate(value) { return toStr.call(value) === "[object Date]"; } function isNumber(value) { return toStr.call(value) === "[object Number]"; } /** * Returns a new Javascript Date object, allowing a variety of extra input types * over the native Date constructor. * * @param {Date|string|number} val */ module.exports = function newDate(val) { if (isDate(val)) return val; if (isNumber(val)) return new Date(toMs(val)); // date strings if (isodate.is(val)) { return isodate.parse(val); } if (milliseconds.is(val)) { return milliseconds.parse(val); } if (seconds.is(val)) { return seconds.parse(val); } // fallback to Date.parse return new Date(val); }; /** * If the number passed val is seconds from the epoch, turn it into milliseconds. * Milliseconds would be greater than 31557600000 (December 31, 1970). * * @param {number} num */ function toMs(num) { if (num < 31557600000) return num * 1000; return num; }