1

How can I convert a date to JSON format using JavaScript or jQuery?

For example: 28/08/2013 or Wed Aug 28 2013 12:09:29 GMT+0530 to:

Date(928129800000+0530)

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
RaviKiran
  • 101
  • 2
  • 3

3 Answers3

2

How can I convert a date to JSON format

JSON has no format for dates. That string you frequently see is a popular convention, nothing more. (And like many conventions, there are variations on that theme.)

Looking at it, it's the underlying Epoch value plus the timezone offset. Both of those pieces of information are available from the Date object. The Epoch value comes from getTime, and the timezone offset from getTimezoneOffset (which is in minutes).

Using those, you can create a string in that form.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

what about this,

I have Edited the code... pls try this,

public class DateHandler : IHttpHandler  
{  

    public void ProcessRequest(HttpContext context)  
    {  
        context.Response.ContentType = "application/json";  
        string action = context.Request.QueryString["jsonmode"];  
        string json = null;  

        if (!string.IsNullOrEmpty(action) && action == ".net")  
        {  
            // Creates date in .NET date format "\/Date(14123123132)\/"  
            JavaScriptSerializer ser = new JavaScriptSerializer();  
            json = ser.Serialize(DateTime.Now);  
        }  
        else  
            // iso format: "2010-08-31T01:35:05.785Z"  
            json = "\"" + DateTime.Now.ToUniversalTime().ToString("s") +   
                   "Z" + "\"";  

        context.Response.Write(json);   
    }  

    public bool IsReusable  
    {  
        get { return false; }  
    }  
}  
Able Alias
  • 3,824
  • 11
  • 58
  • 87
  • Thanks Delphian for your response. I wanted the other way around, the normal date string should be converted to json format something like this "\/Date(928129800000+0530)\/" – RaviKiran Aug 28 '13 at 09:56
  • I have a suggestion, if your date value is javascript, you can convert that value to JSON using JSON.stringify Function – Able Alias Aug 28 '13 at 10:08
0

Try the following simple method

var dateString= "/Date(1224043200000)/"; var date= new Date(parseInt(dateString.substr(6)));

Benhar Upasana
  • 235
  • 2
  • 9