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

To use the toString function from date-fns in JavaScript, first, we need to install the date-fns package using npm.

index.tsx
npm install date-fns
21 chars
2 lines

Then, we can import the toString function from date-fns and use it to format a date in a specific way.

index.tsx
import { toString } from 'date-fns';

const date = new Date();

const formattedDate = toString(date, 'yyyy-MM-dd');
console.log(formattedDate); // Output: '2021-08-25'
168 chars
7 lines

In the above example, we imported the toString function from date-fns and created a new Date object. We then used the toString function to format the date in yyyy-MM-dd format, which is year-month-day format. The resulting formatted date was then logged to the console.

You can use different format strings to format the date according to your requirements. Visit the date-fns documentation for more information about formatting options.

gistlibby LogSnag