Skip to content

Instantly share code, notes, and snippets.

@supernovaplus
Last active June 27, 2022 21:05
Show Gist options
  • Save supernovaplus/1dc1e93f64f99bbb0647e4d89cdc0d9e to your computer and use it in GitHub Desktop.
Save supernovaplus/1dc1e93f64f99bbb0647e4d89cdc0d9e to your computer and use it in GitHub Desktop.
date diff
function getTimeDiffFromNow(timestamp) {
const diff = timestamp - Date.now();
const absDiff = Math.abs(diff);
const dateObj = {
year: Math.floor(absDiff / 31_104_000_000),
month: Math.floor((absDiff / 2_592_000_000) % 12),
day: Math.floor((absDiff / 86_400_000) % 30),
hour: Math.floor((absDiff / 3_600_000) % 24),
minute: Math.floor((absDiff / 60_000) % 60),
second: Math.floor((absDiff / 1_000) % 60),
//millisecond: Math.floor( absDiff % 1000),
};
const finalString = Object.entries(dateObj)
.reduce((acc, [key, val]) => {
if (acc.length < 2 && val !== 0)
acc.push(val + ' ' + (key + (val === 1 ? '' : 's')));
return acc;
}, [])
.join(' and ');
console.log(dateObj);
return diff > 0 ? `In ${finalString}` : `${finalString} ago`;
}
console.log(getTimeDiffFromNow(new Date('2023-06-28').valueOf()));
//In 1 year and 5 days
console.log(getTimeDiffFromNow(new Date('2021-06-28').valueOf()));
//1 year and 4 days ago
console.log(getTimeDiffFromNow(new Date('2020-07-30').valueOf()));
//1 year and 11 months ago
//days will differ because this code thinks that all months have 30 days
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment