Convert new Date() to weekday string eg 'Thursday' using date-fns
Asked Answered
C

4

13

I'm using date-fns I would like to convert new Date(2020,1,10) to 'Thursday'. I'm trying to use

dateFns.format(new Date(2020,1,10),'dddd')

but it returns 0001?

Thanks in advance

Collimate answered 1/10, 2020 at 15:44 Comment(0)
C
30

Use this for full Day name:

import {format} from 'date-fns';

format(new Date(2020,1,10), 'EEEE')
Cryoscope answered 22/4, 2021 at 7:39 Comment(2)
EEEE is the correct answer, but I made the same mistake because of their documentation date-fns.org/v1.30.1/docs/formatTattered
The format string format changed in date-fns v1 -> v2, make sure to switch to the correct version of the documentation in the top right corner, e.g. date-fns.org/v2.29.3/docs/formatMontpelier
V
1

This also works: format(new Date(2020,1,10), 'iiii')

Vantage answered 17/2, 2023 at 15:13 Comment(0)
P
1

"dddd" only works in older versions of date-fns (< 2.0.0) for getting the day of the week. In newer versions, "dddd" is replaced with "EEEE".

Palladium answered 17/10, 2023 at 17:18 Comment(0)
P
0

For me using date ("2022-10-29") and format(new Date(date), 'EEEE') showed wrong weekday Friday instead of Saturday (I am Central Time), from my understanding I need to provide time to get correct weekday.

for some reason this using different "Month Day, Year" format this worked: {format(parseISO(date), "MMMM d, yyyy")} => October 29, 2022

Since I had time in different variable, I have combined, date and time {format(new Date(date + "T" + time + "Z"), "EEEE")} this seem to work, shows correct weekday: Saturday

Policlinic answered 28/10, 2022 at 13:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.