Skip to content

Instantly share code, notes, and snippets.

@RienNeVaPlus

RienNeVaPlus/dateDiff.ts

Last active Aug 1, 2019
Embed
What would you like to do?
🕤 dateDiff() - returns a detail object about the difference between two dates
/**
* ☃ dateDiff "Snowman Carl" (http://stackoverflow.com/questions/13903897)
* Returns a detail object about the difference between two dates
*
* When providing custom units, provide them in descending order (eg week,day,hour; not hour,day,week)
*
* @param {Date} dateStart - date to compare to
* @param {Date|string} [dateEnd=new Date()] - second date, can be used as unit param instead
* @param {...string} [units=Object.keys(dateDiffDef)] - limits the returned object to provided keys
*/
export function dateDiff(
dateStart: Date,
dateEnd: Date | string = new Date,
...units: string[]
): {
[key: string]: number
} {
if(typeof dateEnd === 'string')
dateEnd = new Date();
let delta: number = Math.abs(dateStart.getTime() - dateEnd.getTime());
return (units.length ? units : Object.keys(dateDiffDef))
.reduce((res: object, key: string) => {
if(!dateDiffDef.hasOwnProperty(key))
throw new Error('Unknown unit in dateDiff: '+key);
res[key] = Math.floor(delta / dateDiffDef[key]);
delta -= res[key] * dateDiffDef[key];
return res;
}, {});
}
// default time units for dateDiff
export const dateDiffDef = {
millennium: 31536000000000,
century: 3153600000000,
decade: 315360000000,
year: 31536000000,
quarter: 7776000000,
month: 2592000000,
week: 604800000,
day: 86400000,
hour: 3600000,
minute: 60000,
second: 1000,
millisecond: 1
};
@RienNeVaPlus

This comment has been minimized.

Copy link
Owner Author

@RienNeVaPlus RienNeVaPlus commented Feb 25, 2019

Usage:

console.log(
	'Elapsed time since the sinking of the RMS Titanic:',
	dateDiff( new Date(1912, 3, 15) ), '\n',
	// { millennium: 0, century: 1, decade: 0, year: 6, quarter: 3, month: 2, 
	//  week: 1, day: 5, hour: 0, minute: 51, second: 27, millisecond: 327}

	'Years + months between JavaScript and TypeScript was firstly introduced:',
	dateDiff(new Date(1995, 10, 18), new Date(2012, 9, 1), 'year', 'month')
	// {year: 16, month: 10}
);

When using units, provide them in descending order (week, day, hour instead of hour, day, week).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.