-
-
Save aguynamedben/b1a7a90b1920db3fcbf815d6e29abf37 to your computer and use it in GitHub Desktop.
Relative dates using date-fns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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