开发者

Date and time regular expression

开发者 https://www.devze.com 2023-04-06 05:08 出处:网络
I\'m looking for a regular expression which matches the following datetime format: dd-MMM-yyyy HH:mm:ss (15-Sep-2011 16:00:47)

I'm looking for a regular expression which matches the following datetime format:

dd-MMM-yyyy HH:mm:ss (15-Sep-2011 16:00:47)

Currently I only have the regex for date which looks something like this:

^(3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-](Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-]\d{4}$

Any ideas for the time part?

It's ok guys I found the solution. Submitting for anyone who wants to utilise it.

(3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-](Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-]\d{4}\s(20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?开发者_高级运维\d


Must it be a regex?

DateTime.TryParseExact will work much better.

DateTime myDate;
// dd-MMM-yyyy HH:mm:ss (15-Sep-2011 16:00:47)
if (DateTime.TryParseExact(dateAsString, 
                          "dd-MMM-yyyy HH:mm:ss", 
                          new CultureInfo("en-US"),
                          DateTimeStyles.None,
                          out myDate))
{  ... }


Err, it appears to me that the date bit is the hard one :-) But you can use the same methods for the time.

Assuming you have two fixed digits, you can use something like:

(([01][0-9])|(2[0-3])):[0-5][0-9]:[0-5][0-9]

The first bit is the slightly tricky bit since you want one of:

  • 0 or 1 followed by a digit.
  • 2 followed by 0 thru 3.

The minutes and seconds are both:

  • 0 thru 5 followed by 0 thru 9.

If you want to allow single-digit hours, just replace [01] with [01]?.

You may also want to consider the possibility that people may enter nov or OcT as the month, rendering your regex less useful.

This could be solved with a case-insensitive version which would also reduce the size of the regex as well, requiring only one string per month.


As Joel suggested above that I should add my solution as an answer here. So here it is:

(3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-](Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-]\d{4}\s(20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d

Do let me know if it works out.

0

精彩评论

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