Click here to Skip to main content
15,867,834 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a database table that have date records are "dd.MM.yyyy". eg 21.05.2021
I want serialize to json file as New Date (yyyy, MM, dd)

JavaScript
"date": New Date (2021 , 05 , 21)


How can i do this?

What I have tried:

C#
var jsonSettings = New JsonSerializerSettings();
jsonSettings.DateFormatString = "New Date (yyyy,MM,dd)";
String  jsonKalin  = JsonConvert.SerializeObject(dmKalin, jsonSettings);
Posted
Updated 8-Apr-21 3:55am
v3

1 solution

That's not a valid JSON representation of a date.

Assuming you're trying to generate a Javascript snippet to construct a new Date, you need to bear in mind that the month you pass in is the month index: January = 0, February = 1, etc. So new Date(2021,5,21) represents 21st June, not 21st May.

Date() constructor - JavaScript | MDN[^]

JSON.NET has a built-in converter to generate a correct Javascript snippet for you, even though it's not technically correct JSON:
Serializing Dates in JSON[^]
C#
var jsonSettings = new JsonSerializerSettings
{
    Converters =
    {
        new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter(),
    },
};

string  jsonKalin = JsonConvert.SerializeObject(dmKalin, jsonSettings);
// "date": new Date(1621551600000)
The number passed to the Date constructor represents the number of milliseconds since the UNIX epoch.
 
Share this answer
 
Comments
gacar 8-Apr-21 11:58am    
Thanks for solution. But returned this values

[{"x":"28.09.2009","y":850.0000},{"x":"26.09.2009","y":810.0000},{"x":"27.09.2009","y":810.0000},{"x":"29.09.2009","y":810.0000},{"x":"06.10.2009","y":850.0000},{"x":"08.10.2009","y":850.0000}]

I am using LinqToSQL this is my code

protected void btnKAydet_Click(object sender, EventArgs e)
{
using (var db = new SiteChartCs.App_Start.SiteLinqDataContext())
{
for (int i = 0; i <= 3; i++)
{
var dmKalin = db.Iron.Where(x => x.bolge_id == i + 1).Select(z => new { x = z.short_date, y = z.kalin }).ToList();
string Bolge = "";
if (i == 0)
Bolge = "Location1";
if (i == 1)
Bolge = "Location2";
if (i == 2)
Bolge = "Location3";
if (i == 3)
Bolge = "Location4";

var jsonSettings = new JsonSerializerSettings
{
Converters =
{
new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter(),
},
};

// "date": new Date(1621551600000)

string jsonKalin = JsonConvert.SerializeObject(dmKalin, jsonSettings);
File.WriteAllText(Server.MapPath("~/Content/Chart/iron/" + Bolge + "KalinTum.json"), jsonKalin);
}
}
}
Richard Deeming 8-Apr-21 12:44pm    
Then z.short_date is not a valid DateTime value.

Don't store dates as strings; use a proper date data-type.
gacar 8-Apr-21 13:09pm    
Yes thanks, worked now. But how can i convert to miliseconds to date?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900