开发者

What regular expression should I use to match this date pattern: DAY.month.YEAR?

开发者 https://www.devze.com 2023-03-16 08:45 出处:网络
I have this date format: DAY.month.YEAR (today: 28.06.2011) I will ne开发者_JAVA百科ed a Regular Expression (RegEx) pattern for matching this date format.

I have this date format:

DAY.month.YEAR (today: 28.06.2011)

I will ne开发者_JAVA百科ed a Regular Expression (RegEx) pattern for matching this date format.

Can anyone post a solution for this problem?


Derived from http://www.regular-expressions.info/dates.html:

(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19|20)\d\d

This matches a date in dd.mm.yyyy format from between 01.01.1900 and 31.12.2099. It will, however, still match invalid dates, because validating leap years, for example, can not be done with regex (at least not very easily).

However, a regex is probably unnecessary. Javascript example:

var date = "28.06.2011".split("."); // split up the date by the dots

// parse the components into integers
var day = parseInt(date[0]);
var month = parseInt(date[1]);
var year = parseInt(date[2]);

// if you want the date in a date object, which will fix leap years (e.g. 31.02 becomes 03.03
var date = new Date(year, month - 1, day);

Note that when creating a date object, month starts at zero.

Which method you use depends on what you need this for. If you want to find dates in a text, use the regex. If you simply want to parse the date into a date object, use the second method. Some extra validation is possibly necessary to make sure the date is valid, as the javascript Date object does not care about February having 31 days, it simply wraps over to 3. of March.


If you wish to match the format of the date, than it will be enough to use:

\d\d\.\d\d\.\d\d\d\d

However, as David Hall pointed out in his comment to your question, you will still need to validate the date in your code. Doing this in a regex isn't easy, as you can see from Harpyon answer which - still making a "preliminary check that filter out many wrong possiblities" - also accepts 31.02.2011 as a valid date and misses out on the French revolution (14 July 1789).

0

精彩评论

暂无评论...
验证码 换一张
取 消