Lutaaya Huzaifah Idris
Lutaaya Huzaifah Idris

Reputation: 3990

Format date with date-fns

Am trying to format date with such an example 2021-09-20T12:12:36.166584+02:00 with date-fns library but it doesn't work, what's the right approach ?

Below is my code :

import { format } from 'date-fns'
format(date, 'DD.MM.YYYY')

Upvotes: 6

Views: 16456

Answers (2)

Jan Bouchner
Jan Bouchner

Reputation: 897

We definitely need more information on what the problem is.

But I guess you want to have a day of the month to be formatted so you should put dd instead of DD.

DD = 01, 02, ..., 365, 366

dd = 01, 02, ..., 31

And yyyy instead of YYYY.

And your input param date should be a type of Date:

format(new Date('2021-09-20T12:12:36.166584+02:00'), 'dd.MM.yyyy')

Everything can be found in documentation (https://date-fns.org/v2.24.0/docs/format)

Upvotes: 3

Will Jenkins
Will Jenkins

Reputation: 9787

You have to parse your ISO string before you can format it, and use lowercase dd and yyyy:

import { format, parseISO } from "date-fns";

const dateFormatted = format(parseISO(date), "dd.MM.yyyy");

Upvotes: 11

Related Questions