Category Archives: momentjs

moment.js with locale doesn’t parse locale dates / it displays malformed strings with punctuation

The problem :

So, you wanted to use momentjs to parse from locale date and time and/or month and day names , or you wanted some locale output from date using .format in your browser, but what you received was a mess?

Sample solution to play on/investigate :

Here : https://github.com/rostacik/moment-js-with-locales-demo you can find a sample solution with reproduction of the problem and samples how to fix the problem. Feel free to reuse.

What happened :

Basically the problem is following thing : file moment-with-locales.js with localized names of dates, moths, etc. contains UTF8 characters. But, it is saved as UTF8 without BOM (at least, that is what Notepad++ says). Which is OK for text editors, but browsers needs to know somehow upfront. Otherwise this is going to happen to special characters and in this way they will be parsed :

malformed moment js with locale

The tricky part is, that JavaScript command as such are valid. What is not are string literals with special characters, nothing more.

So how can you tell browser that what we need is this? :

correct moment js with locale

 The solution :

To keep is simple stupid, you either :

  • Use UTF8 with BOM (byte order mark) and you can/need to keep just plain <script reference (but you will need to reencode every new version of moment.js there will be),
  • Use plain <script reference but you will set up yout web server in a way it will add response header for .js files with Content-Type set to application/javascript; charset=utf-8 (normally there is only application/javascript),
  • Use <script tag but force also charset=”utf-8″ on it.

BTW you also need to use <script charset=”utf-8″ on files that are from cdnjs. You can find sample in my github repo.

Hope this helps.

If you have any other ways of making moment.js work with locales in the browser, than please feel free comment under the article or mail me.

Dušan