parse multiple date formats at once

  • Thread starter Thread starter Zeng
  • Start date Start date
Z

Zeng

Hi,

Is there a way to parse datetime in string with following possible formats
into a DateTime object?
- MM/DD/YYYY
- MM/DD/YY
- MM/YY
- MM/YYYY

This line of code would throw if I pass "08/03"
DateTime result = DateTime.Parse( s );

Thanks!
 
REPLY :
instead of datatime use string to accomodate all your
formats then use the CONVERT function Convert.DateTime
(string);
 
Zeng said:
Is there a way to parse datetime in string with following possible formats
into a DateTime object?
- MM/DD/YYYY
- MM/DD/YY
- MM/YY
- MM/YYYY

This line of code would throw if I pass "08/03"
DateTime result = DateTime.Parse( s );

Use DateTime.ParseExact, which takes an array of formats to try one by
one.
 
It seems to work but the format list keep growing (see below), I really need
a simpler way to default the date to the first day of the month, and tell
the parser/convertor to aim for month and year if the input string has only
2 numbers. Is there a way to do that?

private static string[] s_Formats = new string[] {
@"MM/dd/yyyy", @"MM-dd-yyyy", @"MM.dd.yyyy", @"MM\dd\yyyy",
@"M/dd/yyyy", @"M-dd-yyyy", @"M.d.yyyy", @"M\d\yyyy",
@"MM/dd/yy", @"MM-dd-yy", @"MM.dd.yy", @"MM\dd\yy",
@"M/dd/yy", @"M-dd-yy", @"M.dd.yy", @"M\dd\yy",
@"MM/yyyy", @"MM-yyyy", @"MM.yyyy", @"MM\yyyy",
@"MM/yy", @"MM-yy", @"MM.yy", @"MM\yy",
@"M/yy", @"M-yy", @"M.YY", @"M\YY" };
 
Zeng said:
It seems to work but the format list keep growing (see below), I really need
a simpler way to default the date to the first day of the month, and tell
the parser/convertor to aim for month and year if the input string has only
2 numbers. Is there a way to do that?

private static string[] s_Formats = new string[] {
@"MM/dd/yyyy", @"MM-dd-yyyy", @"MM.dd.yyyy", @"MM\dd\yyyy",
@"M/dd/yyyy", @"M-dd-yyyy", @"M.d.yyyy", @"M\d\yyyy",
@"MM/dd/yy", @"MM-dd-yy", @"MM.dd.yy", @"MM\dd\yy",
@"M/dd/yy", @"M-dd-yy", @"M.dd.yy", @"M\dd\yy",
@"MM/yyyy", @"MM-yyyy", @"MM.yyyy", @"MM\yyyy",
@"MM/yy", @"MM-yy", @"MM.yy", @"MM\yy",
@"M/yy", @"M-yy", @"M.YY", @"M\YY" };

Well, you could start by replacing all slashes, backslahes and dots
with dashes, and then just use one of the "columns" in the above.
Alternatively, split on the various delimiters, see how many values
you've got, parse them with Int32.Parse and then call the DateTime
constructor that takes three int parameters.
 
Back
Top