Date parsing with regular expressions in JavaScrip

2019-08-26 17:06发布

I'm using match() in JavaScript to parse a dates from an RSS feed, I just can't get my head around the correct regular expression to find the date format.

Here's the date:

2009-05-11 16:59:20

And the regular expression so far:

if (dateToParse.match(/^\d\d\d\d-\d\d-\d\d/)) {
        dateTimeSeparator = " ";
        monthIndex = 0;
        dayIndex = 1;
        yearIndex = 2;
}

3条回答
beautiful°
2楼-- · 2019-08-26 17:41

I think rather than struggling with regex you should try date.js. It is still in alpha but looks very promising with all its culture specific versions.

查看更多
▲ chillily
3楼-- · 2019-08-26 17:46
/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/

This puts the date in the first to third groups, and the time in the forth to sixth groups.

查看更多
趁早两清
4楼-- · 2019-08-26 17:51

Hopefully this helps:

var digitpattern = /\d+/g,
    datetime = '2009-05-11 16:59:20',
    matches = datetime.match(digitpattern);

console.log ('year = ' + matches[0]);
console.log ('month = ' + matches[1]);
console.log ('day = ' + matches[2]);
console.log ('hour = ' + matches[3]);
console.log ('minutes = ' + matches[4]);
console.log ('seconds = ' + matches[5]);

Or, you might like to use something like DateJS.

查看更多
登录 后发表回答