Skip to content

Instantly share code, notes, and snippets.

@32teeth
Created November 10, 2023 20:22
Show Gist options
  • Save 32teeth/dc526f139d9152c8b1ab005b4d3dba9d to your computer and use it in GitHub Desktop.
Save 32teeth/dc526f139d9152c8b1ab005b4d3dba9d to your computer and use it in GitHub Desktop.
Cheap and dirty date formatter
const date = new Date();
date.setDate(date.getDate() - 2); // Set date to 2 days ago
const now = new Date();
const diffInMilliseconds = now - date;
const seconds = Math.floor(diffInMilliseconds / 1000);
const formatter = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
const formattedDate = formatter.format(
seconds < 60
? -seconds
: seconds < 3600
? -Math.floor(seconds / 60)
: seconds < 86400
? -Math.floor(seconds / 3600)
: now.getDate() === date.getDate() && now.getMonth() === date.getMonth() && now.getFullYear() === date.getFullYear()
? -Math.floor(seconds / 86400)
: now.getMonth() === date.getMonth() && now.getFullYear() === date.getFullYear()
? -Math.floor(now.getDate() - date.getDate())
: -Math.floor(now.getMonth() - date.getMonth()),
seconds < 60
? 'second'
: seconds < 3600
? 'minute'
: seconds < 86400
? 'hour'
: now.getDate() === date.getDate() && now.getMonth() === date.getMonth() && now.getFullYear() === date.getFullYear()
? 'day'
: now.getMonth() === date.getMonth() && now.getFullYear() === date.getFullYear()
? 'day'
: 'month'
);
console.log(formattedDate);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment