Last active
October 2, 2021 02:33
-
-
Save nickscript0/adbbfe697c824b70a0399d57e51ad043 to your computer and use it in GitHub Desktop.
How to migrate from moment.js to date-fns (as the package is way smaller)
This file contains hidden or 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
/** | |
* date-fns v2 is still in alpha, but has built-in Typescript support so best to use it: | |
* Docs: https://date-fns.org/v2.0.0-alpha.16/docs/Getting-Started | |
* | |
* npm install --save date-fns@next | |
*/ | |
// Useful functions to import | |
import { formatDistanceStrict, isAfter, isBefore, format, subDays, isSameDay } from 'date-fns'; | |
//// Samples of replacing common moment.js patterns | |
// Replace d1.fromNow() with | |
function fromNow(otherDate: number) { | |
const now = Date.now(); | |
const relString = formatDistanceStrict(now, otherDate); | |
return isAfter(otherDate, now) ? `in ${relString}` : `${relString} ago`; | |
} | |
// Replace moment's d1.diff(d2, 'minutes') with | |
differenceInMinutes(d1, d2); | |
// Print a string formatted date | |
format(d1, 'MMM d, YYYY - h:mma')} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment