简体   繁体   中英

regExp code to compare a date format like this: DD-MM-YYYY HH-MM-SS

I have the following piece of javascript to compare a DD-MM-YYYY HH-MM-SS date format, but for some reason it doesn't work. Can anyone see what is wrong with it? (mind that there is a whitespace between the date & time.

new RegExp (/^(0?[1-9]|[12][0-9]|3[01])[\/\-\.](0?[1-9]|1[012])[\/\-\.](\d{4})\s([0-1][0-9]|[2][0-3]):([0-5][0-9]):([0-5][0-9])$/)

The actual data I'm matching to this regExp looks like any of the following: 1-1-2013 0:00:00 1/1/2013 0:00:00 01-01-2013 00:00:00 01/01/2013 00:00:00 31-12-2013 23:59:59 These are the max ranges. Note that from 0:00:00 till 9:59:59 the time is noted like that and for 10:00:00 it's 6 digits, preferably it would handle leap years too.

It looks like the delimiter for the time is : and not - . Try:

new RegExp (/^(0?[1-9]|[12][0-9]|3[01])[\/\-\.](0?[1-9]|1[012])[\/\-\.](\d{4})\s([0-1][0-9]|[2][0-3])\-([0-5][0-9])\-([0-5][0-9])$/)

You should keep things small and test little pieces of regex.

You want to allow one-digit for an hour, but you've forgotten to place it in your regex. It should look like that:

([0-9]|[0-1][0-9]|[2][0-3])

Now it works:

regex = new RegExp (/^(0?[1-9]|[12][0-9]|3[01])[\/\-\.](0?[1-9]|1[012])[\/\-\.](\d{4})\s([0-9]|[0-1][0-9]|[2][0-3]):([0-5][0-9]):([0-5][0-9])$/)
match = '1-1-2013 0:00:00'.match(regex)
console.log(match)

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