I'm using JSON to send data to client. However, the date fields get transformed into a timespan format like /Date(1363807800000)/
.
Is there anyway to get rid of it and let server send DateTime
values like 2013/7/21 3:44 PM
to client?
Think of this,
var data = "/Date(1363807800000)/";
var date = new Date(parseInt(data.replace("/Date(", "").replace(")/", ""), 10));
var result = date.getFullYear() + "-" + (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-" + (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " " + (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":" + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes());
Then, use this RegEx to validate it,
/ ^ \ d {4} - \ d { 2} - \e{2} \e{2}:\e{2}:\e{2} $ /
Hope this helps...:)
Here is a solution using Json.NET (you can install it via NuGet):
object testObject = new { Name = "TestName", DateTime = DateTime.Now };
string output = JsonConvert.SerializeObject(testObject, new IsoDateTimeConverter());
Console.Write(output);
Output:
"{\"Name\":\"TestName\",\"DateTime\":\"2013-07-21T15:01:56.2872469+03:00\"}"
In case ISO DateTime format does not work well for you, you can write your own DateTimeConverter to use with SerializeObject function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With