While Converting the DataTable
to Json
File, the field with DateTime
is converting to a */Date(1722796200000)/*? there is any solution to convert the method to a real datetime
or json
datetime
format "2024-08-05T00:00:00"
Structure of DataTable
DataTable dt = new DataTable();
dt.TableName = "TestJson";
dt.Columns.Add("No", typeof(short));
dt.Columns.Add("CDate", typeof(DateTime));
Datatable Format
No | Date |
---|---|
1 | 05/08/2024 00:00:00 |
2 | 06/08/2024 00:00:00 |
Code to add Data to DataTable
dt.Rows.Add(1, Convert.ToDateTime(txtODate.Text));
Convertion process
string JsonData= DataTableToJSONWithJavaScriptSerializer(Dt);
public string DataTableToJSONWithJavaScriptSerializer(DataTable table)
{
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in table.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Serialize(rows);
}
The Result Am getting
[{"No":1,"CDate":"/Date(1722796200000)/"}]
While due to this , when saving to SQL Server it is showing
"Conversion failed when converting date and/or time from character string"
3
Answers
By using the following syntax to solve the issue.
This is the default behavior of
JavaScriptSerializer
according to the documentation.If you want the date to be serialized in ISO8601 format, you should use the Newtonsoft.Json library:
Or using System.Text.Json library: