Similarities and differences
At first glance, the date formats of Java and moment.js are pretty much exchangeable. The pattern to format the date in German locale is “DD.MM.YY HH:mm:ss” in moment.js and “dd.MM.yy HH:mm:ss” in Java. That’s pretty much the same. Except for the capitalization.
And that’s precisely what make the conversion between moment.js and Java such an unpleasant experience. The concepts are the same, many formatting tokens are the same – except for subtle differences. Basically, you have to be careful with the capitalization and the number of characters. For instance, “D” prints the number of the day in the year in Java, but the number of the day in the month in moment.js. The moment.js counterpart of Java’s “D” is “DDD”. Adding insult to injury, “DDD” also denotes the number of the day of the year in Java – but it’s the three digit, zero-padded version. Which is “DDDD” in moment.js.
Formats that can’t be converted
There are also format strings that can’t be converted. For example, Java’s “G” denotes the era (i.e. A.D. or B.C.). There’s no counterpart in moment.js. Luckily, the common use cases are covered.
Sometimes, even the common use cases have surprises in store. The abbreviated versions of the names of the days and months are identical in both Java and moment.js. More precisely: they are identical in English. The Spanish, French and German translations add a dot in Java, but not in moment.js.
Both moment.js and Java’s SimpleDateFormat have predefined formats for the most common use cases. Most of them don’t translate directly into each other. The cheatsheet covers the predefined formats, too. However, this translation table isn’t perfect, and it can’t be: Java defines differerent predefined formats for different locales.
Both moment.js and SimpleDateFormat allow you to add non-format strings, such as spaces, commas, slashes and dashes. These strings are added directly to the formatted date. You can also escape characters. In moment.js characters are escaped by surrounding them with square brackets. SimpleDateFormat does the same by putting the string into single quotes:
Both will output something like “Wed, 26 Mar 2017 at 11:17AM”.
Date patterns cheatsheet
Follow this link to get to the interactive cheatsheet.