How to format date with date-fns?

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
    

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)