C# asp.net 中 DateTime 的 Javascript 序列化没有给出 javascript 日期对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1224793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 13:52:28  来源:igfitidea点击:

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

c#asp.netjavascriptdatetimeserialization

提问by Your Friend Ken

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?

当我在 .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);

            }
        }
    }
}

采纳答案by Your Friend Ken

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;

这似乎有效(感谢 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(")\/\"", ")");
                    }
                }
            }
        }

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

..并且在删除引号并将新前缀添加到 Date 这个 js 现在可以工作了。万岁!

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

回答by andres descalzo

jsonDateNow = String.Format("Date({0},{1},{2})", Date().Now.getYear(), Date().Now.getMonth() -1, Date().Now.getDay());

回答by andres descalzo

This example works

这个例子有效

    JavaScriptSerializer serializer = new JavaScriptSerializer();

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

    string jsonDateNow = serializer.Serialize(dt1);

回答by Chris S

This is a known limitationwith JSON. This answermight help you, specifically:

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

value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));

回答by Ryan Triggs

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

通过一些字符串操作和 eval,您可以创建一个 Date 对象

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

回答by John Reilly

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

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.

它允许将 DateTimes 序列化为 ISO 8601 日期字符串,可以与 JavaScript 日期构造函数一起使用,并且具有人类可读的优点。

回答by Kat Lim Ruiz

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.

这似乎适用于 FF 和 IE。

回答by Furhan

Simple javascript manipulation like this:

像这样简单的 javascript 操作:

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.

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

回答by Zephryl

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

这是一个使用 Date.parse 和 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:

如果您需要时间,请考虑以下事项。我相信这依赖于更新的 javascript 规范:

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)

这是一个使用 jQuery 的选项:(我确定有一种方法可以在这里添加时间)

var lowerBound = $.datepicker.parseDate('yy-mm-dd', "@Model.LowerBound.ToString("yyyy-MM-dd")");

回答by Captain Betty

Slightly simpler string clean up with RegEx:

使用 RegEx 清理稍微简单的字符串:

var myDate = "\/Date(1508821200000)\/";    
var jsDate = new Date(parseInt(myDate.replace(/\D/g, '')));