Reputation: 13406
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.
Upvotes: 0
Views: 2549
Reputation: 20804
This answer is only relevent if it's possible for the database value to be null. That is frequently my own situation, so I wrote this function in a helper class in a class library.
public DateTime? SetDateTimeValue(DataTable dataTableIn
, int rowNumber, string fieldName)
{
DateTime? returnValue = new DateTime?();
DateTime tempValue = new DateTime();
try
{
string fieldValueAsString = dataTableIn.Rows[rowNumber][fieldName].ToString();
result = DateTime.TryParse(fieldValueAsString, out tempValue);
if (result)
returnValue = tempValue;
}
catch
{
returnValue = null;
}
return returnValue;
}
Here is a sample call
DataTable data = dataAccess.GetEmergencyVisitDataFromClinicalApplicationSupport(VisitID);
if (data.Rows.Count == 1)
{
ValueSetter setterOfValues = new ValueSetter();
skip a bunch of lines.
AdmitDecisionDateTime =
setterOfValues.SetDateTimeValue(data, 0, "admit_decision_datetime");
Upvotes: 0
Reputation: 26647
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
.
Upvotes: 1
Reputation: 10089
The row is retrieved as an object. The ToString() method is formatting it. You need to pass the format you want to use to the ToString() method.
Upvotes: 1