Link to home
Start Free TrialLog in
Avatar of 2ooth
2ooth

asked on

RegEx for yyyyMMdd format

I have a csv file that has a date column in the following format yyyyMMdd
eg:- 20011114

i want to parse this date via a RegEx into a format that is acceptable by DateTime class in C#

this is what i have done so far (see code section below)

however i am getting an error "Input string was not in a correct format" when the code enters the following line.


if (!ConvertToDate(int.Parse(m.Groups["year"].Value), int.Parse(m.Groups["month"].Value), int.Parse(m.Groups["day"].Value), out date))



m = Regex.Match(str, @"(?<=^(([2-9]\d{3}|1999)((0[1-9]|1[012])(0[1-9]|1\d|2[0-8])|(0[13456789]|1[012])(29|30)|(0[13578]|1[02])31)|(([2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00))0229)$)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                DateTime date;
                if ((defaultFormat ^ DateTimeFormat.USA_DATE) == DateTimeFormat.USA_DATE)
                {
                    if (!ConvertToDate(int.Parse(m.Groups["year"].Value), int.Parse(m.Groups["day"].Value), int.Parse(m.Groups["month"].Value), out date))
                        return false;
                }
                else
                {
                    if (!ConvertToDate(int.Parse(m.Groups["year"].Value), int.Parse(m.Groups["month"].Value), int.Parse(m.Groups["day"].Value), out date))
                        return false;
                }
                parsedDate = new ParsedDateTime(m.Index, m.Length, -1, -1, date);
                return true;

Open in new window

Avatar of Gurvinder Pal Singh
Gurvinder Pal Singh
Flag of India image

Assuming that month and date starts from 0
[0-9]{1,4}([0][0-9]|[1][0-2])([0-2][0-9]|[3][0-1])
SOLUTION
Avatar of Gurvinder Pal Singh
Gurvinder Pal Singh
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I also agree that you should use the Parse group of methods which are members of the DateTime struct.
Avatar of 2ooth
2ooth

ASKER

Thanks Guys!!!