parse multiple date formats at once

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!
 
D

dabuskol

REPLY :
instead of datatime use string to accomodate all your
formats then use the CONVERT function Convert.DateTime
(string);
 
J

Jon Skeet [C# MVP]

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.
 
Z

Zeng

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" };
 
J

Jon Skeet [C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top