asp.net中的DateTime的Javascript序列化没有提供javascript日期对象?

You*_*Ken 48 javascript c# asp.net serialization datetime

当我在.Net中将DateTime解析为json时,它返回一个字符串(即"\/Date(1249335194272)\/").如何让它返回一个js Date对象构造函数而不是换成字符串?

// 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);

            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*s S 56

这是JSON的一个已知限制.这个答案可能对你有所帮助,特别是

value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));
Run Code Online (Sandbox Code Playgroud)


You*_*Ken 14

这似乎有效(感谢Chris S的想法).在C#中执行替换以从日期对象周围删除字符串包装器;

    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(")\\/\"", ")");
                    }
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

..删除引号并将新前缀添加到日期后,这个js现在有效.万岁!

testCase= <%= jsonESHACase %>;
    if (testCase) {
        document.write(testCase["ClosingDate"].format("MM dd yyyy"));
    }
Run Code Online (Sandbox Code Playgroud)


小智 7

像这样简单的javascript操作:

function(param){
  var date = new Date(parseInt(param.substr(6)));
  return date;
}
Run Code Online (Sandbox Code Playgroud)

将JSON日期作为参数传递给函数,它将返回一个javascript日期.