Reputation: 3276
I'm trying to parse a date. The problem, is my regular expression omits any letter because I want to avoid 01-28-2019 UTC
or any letters outside of the main date. Now, it works fine when the date is formatted like I just listed, however it fails when we get a date formatted like 28-JAN-19
.
var sourceValue = Regex.Replace("28-JAN-19", @"[A-Za-z]", "");
var parsed = DateTime.Parse(sourceValue);
The date I need to parse can be in a few different formats. Can a regular expression be used to handle this? If so, what tweaks are needed to trim any letters outside of the xx-xx-xx
part of the string?
28-JAN-19
28-01-19
28-JAN-19 13:15:00
28-01-19 13:15:00
28-01-2019 13:15:00
Upvotes: 0
Views: 59
Reputation: 48696
This RegEx should match all the examples you provided:
[0-9]{2}-([A-Za-z]{3}|[0-9]{2})-[0-9]{2,4}( [0-9][0-9]?:[0-9][0-9]?:[0-9][0-9])?
It does make a couple of assumptions though, based on your examples. First, it assumes all your dates will always start with a 2-digit day. It also assumes that your month abbreviations will be 3 letters long. It also assumes that your hours, minutes and seconds will all be 2 digits long. Let me know if any of these assumptions are incorrect.
Upvotes: 1
Reputation: 44074
Regular expressions are likely not your best bet. If you know the full set of formats you might encounter then you can use the regular DateTime.ParseExact with a format string. Check for a FormatException
to know if you've successfully parsed the date. If your months are using English abbreviations then be sure to pass in an English culture
DateTime.ParseExact("28-JAN-19", "dd-MMM-yy", new CultureInfo("en"));
Upvotes: 1