Object must be of type string - DataTable

Hi,

I have a datatable with number of columns, one of those columns contain dates.
I want to get the maximum (newest date) in that column in the DataTable.

i tried assigning a variable with the following: maxDate = dtOutput.AsEnumerable().Max(Function(row)row(“modifyDate”)).ToString

MaxDate is a string field.

I keep getting Object must be of type ‘string’.

What i am missing here?

Thanks

hi @sacad

are you looping the for each item

Thanks
Ashwin S

@sacad @AshwinS2

Will you please explain that AsEnumerable() method? What is the purpose of using that.

Hi @Sriram07

Check this

Thanks
Ashwin S

@AshwinS2 I gone through all the explanations but i am not able to understand what purpose they are using this? Will you please explain and make me understand.

Hi @sacad,

What is the dataType of column modifyDate, if it’s string then can’t apply max on it, firstly, you have to convert that string into DateTime format as shown below.

try this,
Assign:

maxDate = dtOutput.AsEnumerable().max(Function(x) CDate(DateTime.ParseExact(x.Item("modifyDate").ToString,"dd/MM/yyyy",System.Globalization.CultureInfo.InvariantCulture))).ToString

Note : Specify the correct date format (dd/MM/yyyy) in query as you have it.

Thanks Samir and others

I tried the above solution but still getting the same issue

So i decided to loop through the datatable and extract one date at a time and then add it to a list before finally checking the Max like List.Max.toString

I did notice when i was looping through my date data had 2 different formats (dd/mm/yyyy and dd/mm/yyyy hh:mm:ss)
Looking at the source data in excel, all the dates are in correct format (dd/mm/yyyy)

I have no idea how this could be, anyone?

I had to check the format of the date for each row before applying:
Datetime.ParseExact(currentRow.ToString,“MM/dd/yyyy HH:mm:ss”,System.Globalization.CultureInfo.InvariantCulture)

or

Datetime.ParseExact(currentRow.ToString,“MM/dd/yyyy”,System.Globalization.CultureInfo.InvariantCulture)

I also noticed that it only works with MM/dd/yyyy and not dd/MM/yyyy :frowning: