Skip to content

Instantly share code, notes, and snippets.

@aguynamedben
Last active March 8, 2022 20:38
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 aguynamedben/b1a7a90b1920db3fcbf815d6e29abf37 to your computer and use it in GitHub Desktop.
Save aguynamedben/b1a7a90b1920db3fcbf815d6e29abf37 to your computer and use it in GitHub Desktop.
Relative dates using date-fns
// Convert a date to "8 month ago", "1 day ago", "15 minutes ago"
// Note: We don't display this if it's older than 2 months ago (i.e. doc seems way stale)
// @flow
import {
formatDistanceToNow,
} from 'date-fns';
export function howLongUntil(upstreamUpdatedAt: number) {
const ageInWords = formatDistanceToNow(
new Date(upstreamUpdatedAt * 1000),
{ addSuffix: true },
);
// date-fns gives "about 7 days ago", we just want "7 days ago"
return ageInWords.replace(/about\s/g, '');
}
function howItsUsed() {
const fullMonthsOld = differenceInMonths(new Date(), upstreamUpdatedAtDate);
// Don't display this string for docs more than 8 weeks old
if (fullMonthsOld >= 2) return null;
return `Updated ${howLongUntil(upstreamUpdatedAt)}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment