Search code examples
javascriptdatelocalemomentjs

Parse japanese datestring with moment.js


How can I parse?

'2015年 Oct月10日 (Sat)'

with moment js?

I've been trying

moment('2015年 Oct月10日 (Sat)', ['DD-MM','DD-MMM','YYYY MMMM DD']);

to no avail..


Solution

  • Moment has very good internationalization support. However, you seem to have a mix of using English short month names with Japanese characters.

    The default localization data for Japanese in moment uses numerical months. You can see the loaded data for the short month names here:

    moment.locale('ja');
    moment.monthsShort()
    // ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"]
    

    However, you can easily customize the locale data, described here.

    moment.locale('ja', {monthsShort: ["Jan月", "Feb月", "Mar月", "Apr月", "May月", "Jun月", "Jul月", "Aug月", "Sep月", "Oct月", "Nov月", "Dec月"]});
    

    Now when you check the short months data, you'll see the values you provided instead.

    Now all of the normal moment functions will make use of this data, so you can simple parse like so:

    moment.locale('ja');
    var m = moment('2015年 Oct月10日 (Sat)', 'll');
    

    Note that the ll format would not include the extra day-of-week info, but moment's parser will forgive that.

    The benefit to adjusting the locale data, rather than striping things away, is that you can now also use moment's format function to create an output string, and it will use the same style.