5

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?

Mehdi Emrani
  • 1,313
  • 2
  • 14
  • 26

3 Answers3

1

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

Morris Miao
  • 720
  • 1
  • 8
  • 19
1

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.

SoftwareFactor
  • 8,430
  • 3
  • 30
  • 34
0

I wrote once this, maybe you could add the string to your json ?

var getDate = function() {
    var date = new Date();
    var prefix = "["
        + date.getDate() + "."
        + (date.getMonth() + 1) + "."
        + date.getFullYear() + " "
        + date.toString().split(" ")[4]
        + "]";
    return prefix;
};
Silom
  • 736
  • 1
  • 7
  • 20