Reputation: 197
I'm getting data from a stored procedure and wonder which is the easiest way to convert DateTime (or date) to string?
recipes.Add(new Recipe
{
RecipeId = reader.GetInt32(recipeIdIndex),
Name = reader.GetString(nameIndex),
Date = reader.GetDateTime(dateIndex), //Date is a string
});
Upvotes: 1
Views: 2459
Reputation: 100527
The best way to convert date to string is not do it at all.
If you have to store date time as strings use DateTime.ToString("o")
or ISO8601 format .ToString("yyyy-MM-dd HH:mm:ss.ttt")
as SynXsiS suggested.
Make sure you know if date is in local or UTC time - you may need to adjust values before displaying to a user.
Upvotes: 1
Reputation: 1898
Assuming reader.GetDateTime() is returning a c# DateTime object, all you need to do is call ToString() on it passing in arguments to format it how you like.
reader.GetDateTime(dateIndex).ToString("yyyy-MM-dd HH:mm:ss.ttt")
Upvotes: 4