LittleDragon
LittleDragon

Reputation: 2437

read yyyy-mm-dd format from XL file

i had add custom cell style for the XL "yyyy-mm-dd" and i am read data from XL file in C# application when i read the date column in the data table i can see its in the other format "mm/dd/yyyy" but i want to validate date format ""yyyy-mm-dd"

try
{
    DateTime.ParseExact(dataRow["ServiceDate"].ToString(), "yyyy-mm-dd", CultureInfo.InvariantCulture); //"2014-11-22"
}

catch
{
    //
}

but this is not working every time is when to catch statement

but my date in correct format in XL file "yyyy-mm-dd " how can i fix this :(

Upvotes: 0

Views: 578

Answers (2)

Stoyan Dimov
Stoyan Dimov

Reputation: 5539

Use DateTime.TryParse(string, out DateTime) which will suppress trowing exception on time validation failure. Pass it in an if statement and it will return true, and assign the result to the second argument if the parsing goes OK. Otherwise returns false. If validation goes OK use the ToString(format) of the date time object to convert it to your preferable format.

DateTime formattedTime;

if (!DateTime.TryParse(dataRow["ServiceDate"], out formattedTime)) {
    // dataRow["ServiceDate"] is not a valid date may be throw an exception
}

formattedTime.ToString("yyyy-mm-dd"); // is your formatted time

DateTime.TryParse Docs

Upvotes: 0

StartCoding
StartCoding

Reputation: 393

This should work:

Convert.ToDateTime(dataRow["ServiceDate"]).ToString("yyyy-mm-dd");

Upvotes: 2

Related Questions