0

Hi I am writing a JSON webservice which returns DateTime.

It is returning the date time in EPOCH format. Is it possible to modify the JSON date format it returns.

Code snippet

  [ServiceContract]
    public interface ITMAppServices
    {
          [OperationContract]
          [WebGet(UriTemplate = "/Test",
          RequestFormat = WebMessageFormat.Json,
          ResponseFormat = WebMessageFormat.Json)]

        DateTime GetData();

    }

Actual implementaiton

public class TMAppServices : ITMAppServices
 {
     public DateTime GetData()
     {
          return DateTime.Now;
     }
 }

i am simply returning datetime.now in C#

Output in EPOCH format :

"/Date(1413399311687+0300)/"

i want output in same format returned by C# Or if I get datetime from SQL

Sunil Kumar
  • 111
  • 1
  • 5
  • `return DateTime.Now;` is returning date in `EPOCH` format ? – Habib Oct 15 '14 at 19:22
  • Yes.Its actually a JSON webservice.. When i am running the service this way http://localhost:64964/TMAppServices.svc/Test it returns "\/Date(1413403048647+0300)\/" – Sunil Kumar Oct 15 '14 at 19:56

1 Answers1

3

It looks like you're writing a WCF service. By default, WCF uses the DataContractJsonSerializer for JSON serialization - which uses this format.

You should consider either replacing it with JSON.Net - or preferably, writing your service with ASP.Net WebAPI instead - which already uses JSON.Net.

JSON.Net will (by default) use the ISO-8601 serialization format. This is the preferred format for sending dates over the wire, especially in JSON. For example, "2014-10-15T21:54:00-07:00".

You should not use DD MM YYYY format, as JSON is intended to be machine readable. If a machine with MM DD YYYY culture attempts to read the string, it could misinterpret the value. For example, "1/2/2014" can be read as either January 2nd, or February 1st.

As an aside - you should probably consider using the DateTimeOffset type in .NET instead of DateTime.

Community
  • 1
  • 1
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575