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

To use the format function from date-fns, you first need to install it using npm or Yarn.

Using npm:

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

Using Yarn:

index.tsx
yarn add date-fns
18 chars
2 lines

After installing, you can import it into your JavaScript file:

index.tsx
import { format } from 'date-fns';
35 chars
2 lines

Once imported, you can use the format function to format a date or time according to a specific format string.

Here's an example of how you can use the format function to format the current date and time:

index.tsx
const currentDate = new Date();
const formattedDate = format(currentDate, 'yyyy-MM-dd HH:mm:ss');
console.log(formattedDate); // Output: "2022-02-22 13:45:30"
159 chars
4 lines

In this example, we are creating a new Date object with the current date and time. We then pass this object, along with the desired format string, to the format function to get a formatted date and time string. Finally, we log the formatted string to the console.

gistlibby LogSnag