Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active July 24, 2019 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfkaye/c8b890e321fd214e23b596be48987443 to your computer and use it in GitHub Desktop.
Save dfkaye/c8b890e321fd214e23b596be48987443 to your computer and use it in GitHub Desktop.
format date as a UTC date string - yyyy-mm-ddThh:mm:dd.mmsZ
/**
* @function formatUTCDateString accepts a string or a number and attempts to
* create a YYYY-MM-DDTHH:MM:DD.MSZ string and return it. If the input cannot
* be parsed into a valid date, the original value is returned.
*
* Function also supports a quoted timestamp as the argument, tries to coerce
* it to produce a valid date string.
*
* Note the JavaScript's Date object does *not* accept a quoted timestamp, as
* follows:
*
* new Date("1563845923981") returns "Invalid Date"
* Date.parse("1563845923981") returns NaN
*
* @param {*} item
* @returns {string}
*/
export function formatUTCDateString(item) {
// First try to parse item as a timestamp (number), then as datestring.
var time = (/^\d+$/.test(item) && new Date(Number(item))) || new Date(item);
if (!Date.parse(time)) {
// If we can't parse date to a valid timestamp, punt.
return item;
}
var utc = {
year: time.getUTCFullYear(),
month: time.getUTCMonth() + 1,
date: time.getUTCDate(),
hours: time.getUTCHours(),
minutes: time.getUTCMinutes(),
seconds: time.getUTCSeconds(),
milliseconds: time.getUTCMilliseconds()
}
Object.keys(utc).forEach(key => {
var value = utc[key];
utc[key] = value < 10 ? '0' + value : value;
});
var utcDate = [
utc.year,
utc.month,
utc.date
];
var utcTime = [
utc.hours,
utc.minutes,
utc.seconds
];
return [
utcDate.join('-'),
'T',
utcTime.join(':'),
'.',
time.getUTCMilliseconds(),
'Z'
].join('');
}
/* format value in as yyyy-mm-ddThh:mm:ss.msZ UTC Date */
describe('formatUTCDateString(value)', () => {
const RE_UTC_STRING = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/;
it('should accept and format a Date timestamp', () => {
var utc = formatUTCDateString(Date.now());
expect(RE_UTC_STRING.test(utc)).toBe(true);
});
it('should accept and format a Date object', () => {
var utc = formatUTCDateString(new Date());
expect(RE_UTC_STRING.test(utc)).toBe(true);
});
it('should accept and format 2019-07-23T01:00:01.477Z', () => {
expect(formatUTCDateString('2019-07-23T01:00:01.477Z')).toBe('2019-07-23T01:00:01.477Z');
});
it('should format 1563845923981', () => {
expect(formatUTCDateString(1563845923981)).toBe('2019-07-23T01:38:43.981Z');
});
it('should format a *quoted* timestamp, "1563845923981"', () => {
// new Date("1563845923981") returns "Invalid Date"
// Date.parse("1563845923981") returns NaN
expect(formatUTCDateString("1563845923981")).toBe('2019-07-23T01:38:43.981Z');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment