I have an excel with date column, values as below. first one is in mm/dd/yyyy format and second one is in dd/mm/yyyy format
6/11/2020
16/06/2020
On fetching the column value using – Row.Item(“Date Of last contact”).ToString
it shows -
06/11/2020 00:00:00
16/06/2020
When i do any kind of date time manipulation, It is giving below exception for 16/06/2020 format -
Assign: String was not recognized as a valid DateTime.
I did - DateDiff (DateInterval.Day, Convert.ToDateTime(DateContacted),Convert.ToDateTime(TodayDate) ).ToString
where DateContacted = value getting from excel
Can anybody help me where I am going wrong?
Thanks
Can you try with this
int_days = DateDiff(DateInterval.Day, DateTime.ParseExact(Strinput.ToString, “dd-MMM-yyyy”, System.Globalization.CultureInfo.InvariantCulture),DateTime.now())
Try the below :
DateContacted = DateTime.ParseExact(Row.Item(“Date Of last contact”).ToString,“dd/MM/yyyy”,System.Globalization.CultureInfo.InvariantCulture)
Then use the DateContacted variable (of type date time) to anykind of manipulations needed.
DateDiff (DateInterval.Day,DateTime.ParseExact(Row.Item(“Date Of last contact”).ToString,"dd/MM/yyyy",System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy"),DateTime.now.Tostring(dd/MM/yyyy)).ToString
@rohith.prabhu - i believe this wont work as date is in different format in excel. while fetching Row.Item … it will come in different format and we need to give the exact format in DateTime.ParseExact(Row.Item(“Date Of last contact”).ToString,“dd/MM/yyyy”,
Hi @Shuchi_Gupta - we can pass multiple formats in the same expression as below to cover all possible formats appearing in the input
DateContacted = DateTime.ParseExact(Row.Item(“Date Of last contact”).ToString,{“dd/MM/yyyy”, “MM/dd/yyyy HH:mm:ss”},System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.None)
ArrString = New String(){"MM/dd/yyyy","dd/MM/yyyy hh:mm:ss","MM/dd/yyyy hh:mm:ss","dd/MM/yyyy"}
DateDiff (DateInterval.Day,DateTime.ParseExact(Row.Item("Date Of last contact").ToString,ArrString,System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.None).ToString("dd/MM/yyyy"),DateTime.now.Tostring("dd/MM/yyyy")).ToString
Same as discussed by Arpan the multiple formats were handled with a format array
About the DateDiff function take a note that not fractions of the selected unit is returned. When this is needed / important let us know for presenting additional techniques