34

I've been trying to format a date using date-fns but I keep failing. Basically I have it working just fine with momentJS but not with date-fns:

Here's my date:

"10-13-20" // month, day, and year

Now with momentJS it works just fine like this:

let result = moment("10-13-20", 'MM-DD-YY').format()
// result = "2020-10-13T00:00:00-06:00"

So I'm trying to do the same using date-fns but no luck. Can anyone point me in the right direction? Thanks in advance!

let result = format(new Date("10-13-20"), 'MM-DD-YY') // Not working
Devmix
  • 1,599
  • 5
  • 36
  • 73
  • `new Date("10-13-20")` returns an invalid Date in Firefox and Safari at least. See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Oct 15 '20 at 06:35

2 Answers2

48

As you can see, with moment lib, we need 2 steps to get the result: parse string to Date object, then format date object to string.

Your code - format(new Date("10-13-20"), 'MM-DD-YY') is format step, try convert a date object to a string with format template is MM-DD-YY. But your date object is not correct.

The solution is to do the same as with moment lib:

  1. Parse date string to date object. Use parse

    const dateString = '10-13-20';
    const date = parse(dateString, 'MM-dd-yy', new Date()) // not MM-DD-YY
    
  2. Format date object to result string. Use format

    const result = format(date, "yyyy-MM-dd'T'HH:mm:ss.SSSxxx")
    console.log(result)
    

    Result will be like (the same with moment's result in my timezone):

     2020-10-13T00:00:00.000+09:00
    
WoJ
  • 27,165
  • 48
  • 180
  • 345
hoangdv
  • 15,138
  • 4
  • 27
  • 48
13
const date = "2021-12-20"
console.log(format(parseISO(date), "dd-MM-yyyy"));
// output: 20-12-2021
Sean Corfield
  • 6,297
  • 22
  • 31
adR
  • 450
  • 6
  • 11