There are multiple method to format and manipulate Date and Time. Generally speaking the most common libraries used to manipulate dates are Day.js, Luxon, Moment, and Date-fns.
Moment developers have discouraged developers to use moments at this time due to not being built for modern JavaScript era.
Day.js
Formats
Luxon usage
npm install --save luxon
Moment usage
import moment from "moment";
And to use the moment library, use the method below (note the bolded text). In the example below, I use calendar function to get the relative date to output on my application.
let formattedDate = moment(date).calendar(null, {
sameDay: '[Today]',
nextDay: '[Tomorrow]',
nextWeek: 'dddd',
lastDay: '[Yesterday]',
lastWeek: '[Last] dddd',
sameElse: ' '
});
Further examples: https://betterprogramming.pub/using-moment-js-in-react-native-d1b6ebe226d4
Date-fns
This date-fns library is a lot lighter to use since you can import a specific function instead of the entire large library. However, it doesn't have certain customized option to allow manipulation of the relative date output similar to above.
Import the function to use similar to below:
import { format, formatRelative } from "date-fns";
To use in the code, you call the simple format date function similar to below:
format(date, "MMM d, yyyy");
Comments
Post a Comment