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"]),
Convert.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
JsonResultformats 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