Search code examples
reactjsecmascript-6date-fns

Convert Date String Using Date-FNS


I would like to convert this string 2022-06-01T14:42:52+00:00 using date-fns. The problem is that its outputting Invalid time value

Code

import { format } from 'date-fns'

let deadlineDate = '2022-06-01T14:42:52+00:00'

console.log(format(deadlineDate, `yyyy-LL-dd`))

Solution

  • You are passing a string to the format function. You should pass the Date object to the format function.

    You can parse the string using parseISO function and then pass it to format

    import { format, parseISO } from "date-fns"
    
    let deadlineDate = parseISO('2022-06-01T14:42:52+00:00')
    
    console.log(format(deadlineDate, `yyyy-LL-dd`))
    
    // "2022-06-01"
    

    Reference: https://date-fns.org/v2.28.0/docs/parseISO