最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Date parsing with regular expressions in JavaScript - Stack Overflow

programmeradmin1浏览0评论

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;
}

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;
}
Share Improve this question asked Jun 30, 2009 at 10:35 TomTom 34.4k31 gold badges89 silver badges111 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2
/^(\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.

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.

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.

发布评论

评论列表(0)

  1. 暂无评论