how to use the parse function from date-fns in javascript

The parse function from date-fns is used to parse a date or string into a new Date object. Here's an example of how to use it:

index.tsx
const dateFns = require('date-fns');

const dateString = '2021-02-22';
const parsedDate = dateFns.parse(dateString, 'yyyy-MM-dd', new Date());

console.log(parsedDate); // Output: Mon Feb 22 2021 00:00:00 GMT+0000 (Coordinated Universal Time)
243 chars
7 lines

In the above example, we first import the date-fns library. We then define the dateString variable to hold our date in string format. The parse function takes three arguments: the first is the string to be parsed, the second is the format of the input string, and the third is the base date to which the parsed date will be added.

The second argument ('yyyy-MM-dd') is the format of the input string, where 'yyyy' represents the year, 'MM' represents the month, and 'dd' represents the day. Finally, we log the parsedDate to the console. You can also use the format function from date-fns to format the parsedDate in a different format if needed.

gistlibby LogSnag