Javascript serialization of DateTime in asp.net is not giving a javascript date object?

前端 未结 10 1911
甜味超标
甜味超标 2020-12-01 06:04

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

相关标签:
10条回答
  • 2020-12-01 06:57

    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,""));
    
    0 讨论(0)
  • 2020-12-01 06:58
    jsonDateNow = String.Format("Date({0},{1},{2})", Date().Now.getYear(), Date().Now.getMonth() -1, Date().Now.getDay());
    
    0 讨论(0)
  • 2020-12-01 06:59

    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"));
        }
    
    0 讨论(0)
  • 2020-12-01 07:00

    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.

    0 讨论(0)
提交回复
热议问题