Search code examples
c#sqldatetimeformatexception

Date read from Database in wrong format?


I'm using DateTime in my C# winforms tool, and I'm storing dates into an SQL database using this line:

iDisc.acquirementDate.ToString("yyyy-MM-dd")

The SQL database field is of DATE type, and when this date is stored, its stored correctly, such as this: 2013-03-14

When I want to the value, I use this line:

DateTime acquirementDate = DateTime.ParseExact(iDiscRow[TableNames.Discs.acquirementDate].ToString(), "yyyy-MM-dd", CultureInfo.InvariantCulture);

However, a FormatException occurs at the above line, because the string being parsed is not a valid DateTime complaint string.

The value this is being parsed is the this: 3/14/2013 12:00:00 AM

What I don't understand is, why is the value read as 3/14/2013 12:00:00 AM, when in the database its stored as 2013-03-14 ?

I'm using SqlDataReader to retrieve the data from database. Can post that code here, but I don't think its needed as its very basic.


Solution

  • It seems that your iDiscRow[TableNames.Discs.acquirementDate] is DateTime already. In that case you just have to cast it.

    DateTime acquirementDate = (DateTime)iDiscRow[TableNames.Discs.acquirementDate];
    

    And reason why you're getting 3/14/2013 12:00:00 AM is that DateTime.ToString() uses current thread culture to trasnform DateTime to string. Since it's WinForm app, I guess this is your Windows system format for DateTime.