Search code examples
javascriptangulardatepipe

`moment` library vs angular `Pipe` in handling Date formatting


I am using both moment library and angular pipe to handle Date object (formatting). The problem I have found is the difference in interpretation of the date format string.

I have java script Date object called formDate =Fri Oct 20 2023 08:30:00 GMT+1100 (Australian Eastern Daylight Time) and I use the format string 'yyyy-MM-dd HH:mm' then:

  • Using angular pipe - expected result

The code: this.datePipe.transform(formDate, 'yyyy-MM-dd HH:mm'); produces '2023-10-20 08:30'

  • Using moment library - incorrect result

moment library code: moment(formDate).format('yyyy-MM-dd HH:mm'); produces '2023-10-Fr 08:30'

Why there is discrepancy between them. Which one should I use to handle the dates.

If I use the format string 'yyyy-MM-DD HH:mm' moment library works as expected (produces output of '2023-10-20 08:30') and pipe does not work (produces output of '2023-10-DD 08:30')


Solution

  • For moment.js, you'll need to use DD instead of dd. Lowercase represent days of the week, explaining the result you are getting.

    http://momentjs.com/docs/#/parsing/string-format/