prgrm
prgrm

Reputation: 3833

Getting dates with multiple possible formats from a string in C#

I am fairly new to C#.

I have to build a script that reads a string and tries to convert it to a Date.

The problem are:

-The dates come in different formats. (International, American, Japanese)

-The dates come with different separators, or none at all.

-The year might be complete or just 2 positions

I have begun by replacing the possible separators:

dateinstring = dateinstring.Replace("-","");
dateinstring  = dateinstring.Replace(".","");
dateinstring = dateinstring.Replace("/","");

Then check the lenght to see if the year is complete (31102012 or 311012 for example)

if(dateinstring.lenght = 8){
//check format with complete date
}else{
//check format with reduced year
}

Now I stumbled upen this function: DateTime.TryParseExact which seems to do the same, but it returns a boolean (true or false) and not the date itself.

Am I missing something? Are there methods in C# that already do this or should I go on with my solution?

Upvotes: 0

Views: 90

Answers (1)

grek40
grek40

Reputation: 13438

Here is a function that I use in a project when the built-in parsing fails - so it only covers additional formats, not the standard ones.

private DateTime? TryParseNumberString(string dateText)
{
    // additional date format options to be accepted
    var extraDateFormats = new[]
    {
        "d.M.",
        "d.M",
        "ddMMyyyy",
        "ddMMyy",
        "ddM"
    };
    foreach (var item in extraDateFormats)
    {
        DateTime test;
        if (DateTime.TryParseExact(dateText, item, null, System.Globalization.DateTimeStyles.AssumeLocal, out test))
        {
            return test;
        }
    }
    return null;
}

The approach was basically, that I thought of some additional date representations that I want to support and the order of evaluation so that ambiguous strings are evaluated according to my wishes.

Depending on your requirements you may alter the format string array and maybe add a specific culture in case you want to support long date formats with written day / month.

You can also try DateTime.TryParse(input, culture, DateTimeStyles.None, out result) with different culture values, in order to try-parse english, japanese and others by convention.

Upvotes: 1

Related Questions