Regular expression for dd-mm-yyyy hh: mm
I want to check a date in format dd-mm-yyyy hh:mm
, now I am using
/^(0[1-9]|1\d|2\d|3[01])\-(0[1-9]|1\d|2\d|3[01])\-(19|20)\d{2}$/
regex to match date in format dd-mm-yyyy
But I want to check the format dd-mm-yyyy hh:mm
. Can anyone change this regex for the format dd-mm-yyyy hh:mm
?
source to share
Given that dates are irregular (with a different number of days in each month depending on the month, year and century, they are not very good for regular expressions, at least for validation.
For example, a regex that guarantees you don't get Feb 30 or Feb 29 (unless the year is a multiple of 4, not a multiple of 100, unless it is also a multiple of 400) would be truly awful.
I would suggest just using a very simple regex to check for formatting like:
\d{2}-\d{2}-\d{4} \d{2}:\d{2}
and then fetching individual fields for individual validation checks in your code.
Regular expressions are powerful, but like any tool, you need to know when (and when not to use it). This is a sign of a true helper.
Anyway, your regex is suffering from the Y2.1K issue. When you hit 2100, it will stop working. And don't think that you have a lot of time, we thought the same for Y2K :-)
source to share
Regular expression for date format dd-mm-yyyy hh: mm
^([1-9]|([012][0-9])|(3[01]))\-([0]{0,1}[1-9]|1[012])\-\d\d\d\d\s([0-1]?[0-9]|2?[0-3]):([0-5]\d)$
Javascript example: /^([1-9]|([012][0-9])|(3[01]))\-([0]{0,1}[1-9]|1[012])\-\d\d\d\d\s([0-1]?[0-9]|2?[0-3]):([0-5]\d)$/.test('12/12/2017 12:45')
returns true
/^([1-9]|([012][0-9])|(3[01]))\-([0]{0,1}[1-9]|1[012])\-\d\d\d\d\s([0-1]?[0-9]|2?[0-3]):([0-5]\d)$/.test('12/12/2017 12:65')
returns false
source to share
If you are sure it will always be dd
, not d
etc. ( mm
vs m
), you can use:
/\d{2}-\d{2}-\d{4} \d{2}:\d{2}/
If, however, you are not sure if it will always be dd
, but it might be simple instead d
, I suggest:
/\d{1,2}-\d{1,2}-\d{2,4} \d{1,2}:\d{2}/
I left minutes like \d{2}
because I never saw 1:05 pm written as 1: 5.
Of course, this will just confirm that it fits the correct format more or less - it won't check crazy dates like "February 99". Considering the removal of this answer, as others are better.
source to share