Question

I read cell values from excel file that has a several data type (string , dateTime , int) .
And In DateTime cell , that may be in various format likes 12/28/2013 , 8:30 .

Using this code , ( cell.ToString() is excel cell value )

DateTime _dt;
if (DateTime.TryParse(cell.ToString(), out _dt))
{
   //
} 

When I read 12/28/2013 , it return 12/28/2013 12:00:00 AM .
But when I read 8:30 , it return 12/31/1899 12:00:00 AM .
As you can see , I can't get the original time 8:30 .
Am I wrong something ? OR is there any approach to fix it ?

Was it helpful?

Solution

You can use TryParseExact and specify your formats. There is an overload taking string[] patterns array as a parameter:

DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime)

You can call it like that:

DateTime.TryParseExact(cell.ToString(), new [] { "M/d/yyyy", "hh:mm" }, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out _dt);

You may need Custom Date and Time Format Strings to prepare more patterns to make sure it works for all your input formats.

OTHER TIPS

Try like this

string strDate = "8:00";
string format = "hh:mm";
DateTime res;
bool success = DateTime.TryParseExact(strDate, format, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out res);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top