Joe Honton
1 min readJun 7, 2020

--

Creating a class that contains only static properties and methods is a good way to modularize utility functions, placing them contextually into thematic groups. This prevents the global namespace from being polluted. For example:

export default class DateUtils { static addDays(date, numDays) {
return new Date(date.valueOf() + (numDays*24*60*60*1000));
}
static diffDays(date) {
if (date.constructor.name == 'String')
date = new Date(date);
var nowTS = new Date().valueOf();
var dateTS = date.valueOf();
return Math.ceil((dateTS - nowTS) / (24*60*60*1000));
}
static format(date, fmt) {
if (date == null)
return '';
if (date.constructor.name == 'String')
date = new Date(date);
if (Number.isNaN(date.getFullYear()) ||
Number.isNaN(date.getMonth()) ||
Number.isNaN(date.getDate()))
return '';
switch (fmt) {
case 'YYYY-MM-DD':
let YYYY = (date.getFullYear()).toString();
let MM = (date.getMonth() + 1).toString().padStart(2, '0');
let DD = (date.getDate()).toString().padStart(2, '0');
return `${YYYY}-${MM}-${DD}`
case 'Month Day, Year':
let YYYY = (date.getFullYear()).toString();
let MM = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug',
'Sep','Oct','Nov','Dec'][date.getMonth()];
let DD = (date.getDate()).toString();
return `${MM} ${DD}, ${YYYY}`
default:
throw new Error(`unhandled date format ${fmt}`);
}
}
}

--

--

Joe Honton
Joe Honton

Written by Joe Honton

Princeps geographus, Read Write Tools

Responses (6)