How do I properly convert SQL datetime into C# datetime?
I have data stored in a SQL database that I'm attempting to read into an ASP.NET MVC application. I can get the data just fine - but the datetimes are not translating into anything useful.
Here's what I have so far (some data redacted as "..."):
public JsonResult GetXYZByStatusJson()
{
var sqlConn = new SqlConnection(...);
var command = new SqlCommand("...", sqlConn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@status", 0);
sqlConn.Open();
var sqlResult = command.ExecuteReader();
var collection = new Collection<Object>();
while (sqlResult.Read())
{
collection.Add(new XYZ(
...
Convert.ToDateTime(sqlResult["DateSent"]),
Conv开发者_StackOverflow社区ert.ToDateTime(sqlResult["DateDue"]),
...
));
}
sqlResult.Close();
sqlConn.Close();
return Json(collection);
}
The resulting JSON is formatted fine, but the dates look like "\/Date(1294120800000)\/"
How do I properly cast the SQL datetime into a C# DateTime? Using .ToString() doesn't have any affect.
There are nothing wrong with the conversion between Sql Server and C#.
The problem is how JsonResult
formats the string.
The following SO question shows how you can process it at client side: How do I format a Microsoft JSON date?
The other way is to create your own alternative to JsonResult
If it is SQL Server, sqlResult["DateSent"].ToString() will give you something like this: "6/9/1999 12:00:00 AM, 8/15/1999 12:00:00 AM"
Use the built-in string methods (.IndexOf(), .Remove(), etc), or create your own, to parse whatever you need out of this string.
精彩评论