1
votes

I'm testing a piece of code to see if the rules will work each time, so I just made a short console application that has 1 string as an input value which I can replace at any time.

string titleID = "document for the period ended 31 March 2014";
// the other variation in the input will be "document for the period 
// ended March 31 2014"

What I'm doing is I take a specific part from it (depending if it contains a specific word - nvm the details, there is a consistency so I don't worry about this condition). Afterwards I'm taking the rest of the string after a specific position in order to do a DateTime.ParseExact

Ultimately I need to figure out how to check if the first DateTime.ParseExact has failed to then perform a second attempt with a different custom format.

This is how it looks like:

if(titleID.Contains("ended "))
{
    // take the fragment of the input string after the word "ended"                    
    TakeEndPeriod = titleID.Substring(titleID.LastIndexOf("ended "));
    // get everything after the 6th char -> should be "31 March 2014"
    GetEndPeriod = TakeEndPeriod.Substring(6);

    format2 = "dd MMMM yyyy"; // custom date format which is mirroring
                              // the date from the input string

    // parse the date in order to convert it to the required output format
    try
    {
        DateTime ModEndPeriod = DateTime.ParseExact(GetEndPeriod, format2, System.Globalization.CultureInfo.InvariantCulture);

        NewEndPeriod = ModEndPeriod.ToString("yyyy-MM-ddT00:00:00Z");
        // required target output format of the date
        // and it also needs to be a string

    }
    catch
    {
    }
}
// show output step by step
Console.WriteLine(TakeEndPeriod);
Console.ReadLine();
Console.WriteLine(GetEndPeriod);
Console.ReadLine();
Console.WriteLine(NewEndPeriod);
Console.ReadLine();

Everything works fine until I try a different input string, f.eg. "document for the period ended March 31 2014"

So in this case if wanted to parse "March 31 2014" I'd have to switch my custom format to "MMMM dd yyyy" and I do that and it works, but I cannot figure out how to check if the first parse fails in order to perform the second one.

First parse - > success -> change format and .ToString |-> check if failed , if true do second parse with different format -> change format and .ToString

I've tried

if (String.IsNullOrEmpty(NewEndPeriod))
{ do second parse }

Or

if (NewEndPeriod == null)
{ do second parse }

But I get a blank result at Console.WriteLine(NewEndPeriod);

Any ideas how to approach this?

** EDIT: **

Adding here an alternative answer I got which is using Parse instead of TryParseExact, since Parse will handle both of the format variations without the need to specify them

DateTime DT = DateTime.Parse(GetEndPeriod);
//The variable DT will now have the parsed date.
NewEndPeriod = DT.ToString("yyyy-MM-ddT00:00:00Z"); 
1
"Ultimately I need to figure out how to check if the first DateTime.ParseExact has failed to then perform a second attempt with a different custom format." You can also use the overload of ParseExact which accepts a string[] for all allowed formats. Apart from that the TryParse methods are what you're looking for. Never do: catch{ }Tim Schmelter
use tryparseexact rather than parseexactKevin Cook

1 Answers

4
votes

but I cannot figure out how to check if the first parse fails in order to perform the second one

Instead of DateTime.ParseExact use DateTime.TryParseExact that will return a bool indicating if parsing was successful or not.

DateTime ModEndPeriod;
if (!DateTime.TryParseExact(GetEndPeriod, 
                            format, 
                            CultureInfo.InvariantCulture, 
                            DateTimeStyles.None, 
                            out ModEndPeriod))
{
    //parsing failed
}

You can also use multiple formats for parsing using the DateTime.TryParse overload which takes an array of formats:

string[] formatArray = new [] { "dd MMMM yyyy","MMMM dd yyyy"};

DateTime ModEndPeriod;
if (!DateTime.TryParseExact(GetEndPeriod, 
                            formatArray, 
                            CultureInfo.InvariantCulture, 
                            DateTimeStyles.None, 
                            out ModEndPeriod))
{
    //parsing failed
}