String To DateTime Variable Conversion

I got these two strings. strA=“31/01/2021” and strB=“01.31.2021”. Now I make strA to a DateTime variable by doing that: dateA=DateTime.ParseExact(strA,“dd/MM/yyyy”,System.Globalization.CultureInfo.InvariantCulture)

Now my question - how can I make strB be the same as dateA? what do I have to “use” on strB? Is there a simple easy solution?

Hi @rpadevquick ,

You could use the same Expression but format governing the strB string :

DateTime.ParseExact(strB,"MM.dd.yyyy",System.Globalization.CultureInfo.InvariantCulture)

or

CDate(strB)

Amazing, thank you! :slight_smile:

1 Like

What do you mean make them the same? Both are strings, not datetimes. Datetimes don’t have a format - they store a value. Just like how numeric datatypes don’t have formats. You apply a format when outputting them as a string.

If you want to parse strB into a datetime, you do it the same way, but provide the format for strB.

DateTime.ParseExact(strB,“mm.dd.yyyy”,System.Globalization.CultureInfo.InvariantCulture)

Hi @rpadevquick

You can also give various formats while parsing

For dateA

DateTime.ParseExact(strA,{“MM.dd.yyyy”,”MM/dd/yyyy”},System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.None)

For date B

DateTime.ParseExact(strB,{“MM.dd.yyyy”,”MM/dd/yyyy”},System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.None)

Regards
Sudharsan

1 Like

That’s really slick, I never knew you could do that with ParseExact! Very useful if you have multiple possible formats.

Totally agree, thanks everyone! :slight_smile:

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