Parsing datetime with varying format

Hello

Is it possible to parse string with varying format to datetime?
Eg. if the date could be either “20-6-2024” or “20-06-2024” or “1-12-2024” etc.

So the day-month-year will always be in the same spot, but the leading zero might be missing from days/months below 10.

I was hoping that the code below would automatically ajust for missing zeroes after defining the separator (-) but that is not the case.

DateTime.ParseExact("20-6-2024","dd-MM-yyyy",New System.Globalization.CultureInfo("da-DK")).ToString("dd-MM-yyyy")

I know that you could split the date and verify count of characters but I was wondering if there is a wildcard or such, that you could define in the convertion in stead.

Regards
Soren

Hi @SorenB

You can use a wildcard-style format in ParseExact by handling multiple possible date formats using DateTime.TryParseExact or by defining several formats. You can try something like this:

formats = {“d-M-yyyy”, “dd-MM-yyyy”, “d-MM-yyyy”}

If DateTime.TryParseExact(dateStr, formats, New System.Globalization.CultureInfo(“da-DK”), System.Globalization.DateTimeStyles.None, result) Then
Console.WriteLine(result.ToString(“dd-MM-yyyy”))

Make sure that result variable type is DateTime

Hope this helps.

formats is array of Strings?

I cant get this to work.

Assign str_Date = "20-6-2024"
Assign arr_Formats = {"dd-MM-yyyy","d-MM-yyyy","dd-M-yyyy"}

DateTime.TryParseExact(str_Date,arr_Formats,New System.Globalization.CultureInfo("da-DK")).ToString("dd-MM-yyyy")

Yes the type is String Array.

Here is an example workflow for you:


You can use ParseExact function in an Assign activty. Also if you want to use TryParseExact function, it must be in the if condition because it returns a boolean value

1 Like

Thank you.

Apparently it was the DateTimeStyles.None that was required.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.