Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to change date time formatting in JSON?

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?

like image 353
Mehdi Emrani Avatar asked Nov 02 '22 18:11

Mehdi Emrani


2 Answers

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...:)

like image 97
Morris Miao Avatar answered Nov 08 '22 04:11

Morris Miao


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.

like image 37
SoftwareFactor Avatar answered Nov 08 '22 03:11

SoftwareFactor