Search code examples
javascriptdate-formatdate-fns

date-fns formats date incorrectly


Using date-fns I am trying to format the following yyyy/mm/dd

2022-10-26 

to

2022/26/10

Here is my code:

    const date = document.getElementById('date').value
    console.log('Date -> ', date) // date is correct here
    const formatDate = format(new Date(date), 'yyyy/dd/mm');

For 2022-10-26 date-fns outputs the following:

 2022/25/00

Can anyone tell me what is going wrong here and how to correctly format the date as yyyy/dd/mm.


Solution

  • The issue is because according to the date-fns documentation, mm is minutes with leading zeros. You need to use MM for months:

    const formatDate = format(new Date(date), 'yyyy/dd/MM');