简体   繁体   中英

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..

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.

Once you remove Japanese characters,It works all fine.at least so far I've tested.

var test = moment('2015年 Oct月10日 (Sat)'.match(/[a-zA-Z0-9]/g).join(""),"YYYY-MMM-DD");
test.toLocaleString();
//output : "Sat Oct 10 2015 00:00:00 GMT+0900"

This works fine:

moment('2015年 Oct月10日 (Sat)','YYYY- MMM-DD-');
//                                ^^^

You were just missing a placeholder for the 年. - works as an "ignore this char" character.

moment.locale('ja');
var d = moment().format('今: YYYY年M月D日 (ddd) HH時mm分ss秒');
console.log(d);

-> 今: 2018年10月9日 (火) 11時03分06秒

jsfiddle.net/369shdep/33/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM