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

To use the formatRFC3339 function from the date-fns package in JavaScript, you would first need to install date-fns using npm:

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

Then, you can import the formatRFC3339 function and use it to format a Date object as a string in the RFC 3339 format:

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

const date = new Date();
const formattedDate = formatRFC3339(date);

console.log(formattedDate); // Output: 2022-09-14T15:30:00.000Z
176 chars
7 lines

The formatRFC3339 function automatically converts the date object to UTC before formatting it. If you want to format a date object in a specific timezone, you can use the format function with a timezone code:

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

const date = new Date();
const timezone = 'America/New_York';
const formattedDate = format(date, 'yyyy-MM-dd\'T\'HH:mm:ss.SSSXXX', { timeZone: timezone });

console.log(formattedDate); // Output: 2022-09-14T11:30:00.000-04:00
265 chars
8 lines

In this example, the format function from date-fns-tz is used to format the date object in the America/New_York timezone. The \'T\' string is used to escape the 'T' character so that it is included in the formatted string.

gistlibby LogSnag