Convert datatable string to datetime

Hi Forum,

I’m having issue trying to convert a string to datetime format. I’m reading a Excel file and after that I’ll need to compare dates. The format is as below:

image

I’m looping thought the datatable and for each row I’m assigning the data cell to a string:
str_TimeStamp
“17-1-2024 14:14”

and then converting the string to datetime:
Datetime.ParseExact(str_TimeStamp,“dd-m-yyyy hh:mm”,System.Globalization.CultureInfo.InvariantCulture)

After this the idea is to assign the value as datetime back to the datatable to be compared in a later stage of the process.

I’m getting an error:
Multiple Assign: Can not assign ‘Datetime.ParseExact(str_TimeStamp,“dd-m-yyyy hh:mm”,System.Globalization.CultureInfo.InvariantCulture)’ to ‘date_TimeStamp’.

date_TimeStamp is a variable in datetime format.

Any idea of what I could do to convert it to datetime? Ideally the format shoudl be MM-dd-yyyy hh:mm

Many thanks.

@roberto.piccolli

StrDate = DateTime.ParseExact(str_TimeStamp, "d-M-yyyy HH:mm", System.Globalization.CultureInfo.InvariantCulture).ToString("MM-dd-yyyy hh:mm")
date_TimeStamp=DateTime.ParseExact(StrDate,"MM-dd-yyyy hh:mm",System.Globalization.CultureInfo.InvariantCulture)

Hi @roberto.piccolli

Try the below syntax:

str_TimeStamp="17-1-2024 14:14"
Output= Datetime.ParseExact(str_TimeStamp,"d-M-yyyy HH:mm",System.Globalization.CultureInfo.InvariantCulture).ToString("MM-dd-yyyy HH:mm")

Output is of datatype System.String

@roberto.piccolli

It’s not possible to change the Time format for DateTime datatype variables it will automatically pick the system format . We can do it by converting it to string datatype and we can mention the date format.

Hope you understand!!

Hi @roberto.piccolli

str_TimeStamp = "17-1-2024 14:14"
date_TimeStamp = DateTime.ParseExact(str_TimeStamp, "dd-M-yyyy HH:mm", System.Globalization.CultureInfo.InvariantCulture)
date_TimeStampString = date_TimeStamp.ToString("MM-dd-yyyy HH:mm")

date_TimeStamp is the datetime variable
date_TimeStampString is the string variable

Hope it helps!!

Hi @roberto.piccolli

str_TimeStamp=“17-1-2024 14:14”

Try This :

Datetime.ParseExact(str_TimeStamp,"d-M-yyyy HH:mm",System.Globalization.CultureInfo.InvariantCulture).ToString("MM-dd-yyyy HH:mm")

Hope it will helps you :slight_smile:
Cheers!!

@roberto.piccolli

It is important to know the format you are getting from excel …for that either open the data table in locals panel and check or try to print using log message

Generally the format would be Mm/dd/yyy HH:mm:ss

And mostly issue is format only…you would come to know by expanding exception details or by using assign instead of multiple assign

Cheers

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