48

When I parse a DateTime to json in .Net it returns a string (i.e. "\/Date(1249335194272)\/"). How do I make it return a js Date object constructor not wrap in a string?

// js server code
var dteNow = <%= jsonDateNow %>;


// js rendered code
var dteNow = "\/Date(1249335477787)\/";


// C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;

namespace testing{
    public partial class iTaxPrep : System.Web.UI.Page
    {
        protected string jsonDateNow;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                jsonDateNow = new JavaScriptSerializer().Serialize(DateTime.Now);

            }
        }
    }
}
Your Friend Ken
  • 8,644
  • 3
  • 32
  • 41

10 Answers10

56

This is a known limitation with JSON. This answer might help you, specifically:

value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));
Community
  • 1
  • 1
Chris S
  • 64,770
  • 52
  • 221
  • 239
  • 1
    That is pretty much what I ended up doing but when I parse a large object containing several dates and other info this will start looking ugly. – Your Friend Ken Aug 04 '09 at 15:25
  • This works fine for me: value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""))); I guess the 10 in the second arguments not necessary as it appends time 10:00 in the date. Dates I am working on are coming from server and they have the time configured in it, so I don't want that to be changed. Thanks for your answer though! – dhruvpatel Oct 03 '14 at 19:46
  • The 10 in the second argument is necessary, it is the radix argument for parseInt. It does not append anything. It specifies the type the radix or base, and without it may behave differently on different systems. – inki Oct 07 '14 at 16:53
  • @webdeveloper the parseInt argument is in `Javascript The Good Parts` (definitely worth a read) - it's one of the many hidden features of Javascript. It assumes you are base 8 basically – Chris S Oct 09 '14 at 21:19
14

This seems to work (Thanks Chris S for the idea). In the C# do a replace to remove the string wrapper from around the date object;

    using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.UI;
        using System.Web.Script.Serialization;
        using System.Web.Script.Services;
        using System.Web.Services;
        using System.Web.UI.WebControls;

        namespace test
        {
            [ScriptService]
            public partial class testing: System.Web.UI.Page
            {
                protected string strCaseID;
                protected string jsonCase;

                protected void Page_Load(object sender, EventArgs e)
                {
                    if (!IsPostBack)
                    {
                        strCaseID =Tools.GetQueryObject("id");
                        // get a complex object with dates, string, arrays etc.
                        jsonESHACase = new JavaScriptSerializer().Serialize(objCase.Get(strCaseID ))
                            .Replace("\"\\/Date(", "new Date(").Replace(")\\/\"", ")");
                    }
                }
            }
        }

..and after removing the quotes and adding the new prefix to Date this js now works. Hooray!

testCase= <%= jsonESHACase %>;
    if (testCase) {
        document.write(testCase["ClosingDate"].format("MM dd yyyy"));
    }
Your Friend Ken
  • 8,644
  • 3
  • 32
  • 41
  • 1
    I much prefer this answer to the other answers that fix the problem in JS. The problem is in .Net, so should be resolved in .Net IMO. – Carl Sharman Nov 02 '12 at 14:46
7

Simple javascript manipulation like this:

function(param){
  var date = new Date(parseInt(param.substr(6)));
  return date;
}

Pass in JSON date as param to the function and it will return a javascript date.

Furhan
  • 71
  • 1
  • 1
4

With a little string manipulation and an eval you can create a Date object

var dteNow = "\/Date(1249335477787)\/";
var dteObj = eval("new " + dteNow.replace(/\//g,""));
1

You can try this:

"MyField: " + string.Format("(function(y,m,d,h,mm,s){{var d=new Date(Date.UTC(y,m-1,d,h,mm,s));return d;}})({0},{1},{2},{3},{4},{5})", d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second);

This seems to work in FF and IE.

Kat Lim Ruiz
  • 2,425
  • 2
  • 26
  • 32
1

Slightly simpler string clean up with RegEx:

var myDate = "\\/Date(1508821200000)\/";    
var jsDate = new Date(parseInt(myDate.replace(/\D/g, '')));
VincenzoC
  • 30,117
  • 12
  • 90
  • 112
Captain Betty
  • 360
  • 3
  • 10
0

Here's an option using Date.parse and DateTime.ToString:

var lowerBound = new Date(Date.parse("@Model.LowerBound.ToString("MMMM dd, yyyy")"));

If you need time, consider the following. I believe this relies on a newer javascript spec:

var lowerBound = new Date(Date.parse("@Model.LowerBound.ToUniversalTime().ToString("s")"));

Here's an option using jQuery:(I'm sure there's a way to add the time here)

var lowerBound = $.datepicker.parseDate('yy-mm-dd', "@Model.LowerBound.ToString("yyyy-MM-dd")");
Zephryl
  • 343
  • 2
  • 9
-1

I've found that this is a useful technique for dealing with this problem:

http://icanmakethiswork.blogspot.co.uk/2012/04/beg-steal-or-borrow-decent-javascript.html

It allows DateTimes to be serialised as ISO 8601 date strings which can be used with the JavaScript Date constructor and has the bonus of being human readable.

John Reilly
  • 5,791
  • 5
  • 38
  • 63
  • A lot of your answers seem to contain very little content beyond just a link to your blog post. Any chance you can expand upon them to make them into real answers? The rest look great and I'm sure the blog posts will make great answers as well. – Flexo Apr 01 '13 at 19:18
-1
jsonDateNow = String.Format("Date({0},{1},{2})", Date().Now.getYear(), Date().Now.getMonth() -1, Date().Now.getDay());
jcolebrand
  • 15,889
  • 12
  • 75
  • 121
andres descalzo
  • 14,887
  • 13
  • 64
  • 115
-3

This example works

    JavaScriptSerializer serializer = new JavaScriptSerializer();

    DateTime dt = DateTime.Now;
    DateTime dt1 = dt;

    string jsonDateNow = serializer.Serialize(dt1);
andres descalzo
  • 14,887
  • 13
  • 64
  • 115