Click here to Skip to main content
16,018,904 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI Experts, I have a Data table where i am reading the values from a excel file, The datatype its taking is string. I have a column 4 with DateTime format. But its reading as string. How do i convert String to DateTime format. I just have one column to change the Datatype. Please help?

What I have tried:

DataTable dtCloned = dt.Clone();
dtCloned.Columns[4].DataType = typeof(DateTime);
foreach (DataRow row in dt.Rows) 
{
    dtCloned.ImportRow(row);
}
Posted
Updated 21-Jun-18 6:56am
Comments
Richard MacCutchan 21-Jun-18 10:57am    
I have just tried this and it reads the fields correctly as DateTime types. Are you sure that is what you have in the Excel file?
MadMyche 21-Jun-18 11:30am    
What format is the supposed DateTime in?
Bryian Tan 21-Jun-18 12:59pm    
I think the column is smart enough to automatically convert the string into DateTime object if the string is a valid datetime format. To test it out, you can include a random string in column 4, at runtime, the system will throw the error "The string was not recognized as a valid DateTime" -- That my assumption based on the posted code. and by the way, the code and approach look fine although the title of the post not see eye to eye.

1 solution

You can't change the column datatype if a DataTable has data in it.

You can try making sure the column is set to be a date/time in excel before reading it.

I wrote an article that includes code which allows you to import xlsx or csv files, and if you want/need to, you can manually specify the datatype for each column, or let the code finger it out on its own.

CSV/Excel File Parser - A Revisit[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900