如何解析 JSON 以接收 JavaScript 中的 Date 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4511705/
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-23 12:43:35  来源:igfitidea点击:

How to parse JSON to receive a Date object in JavaScript?

javascriptjsondatetime

提问by Piotr Owsiak

I have a following piece of JSON:

我有以下一段 JSON:

\/Date(1293034567877)\/

which is a result of this .NET code:

这是此 .NET 代码的结果:

var obj = DateTime.Now;
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.Serialize(obj).Dump();

Now the problem I am facing is how to create a Date object from this in JavaScript. All I could find was incredible regex solution (many containing bugs).

现在我面临的问题是如何在 JavaScript 中从 this 创建一个 Date 对象。我所能找到的只是令人难以置信的正则表达式解决方案(许多包含错误)。

It is hard to believe there is no elegant solution as this is all in JavaScrip, I mean JavaScript code trying to read JSON (JavaScript Object Notation) which is supposed to be a JavaScript code and at this moment it turns out it's not cause JavaScript cannot do a good job here.

很难相信没有优雅的解决方案,因为这一切都在 JavaScrip 中,我的意思是 JavaScript 代码试图读取 JSON(JavaScript 对象表示法),它应该是一个 JavaScript 代码,目前事实证明这不是因为 JavaScript 不能做好这里。

I've also seen some eval solutions which I could not make to work (besides being pointed out as security threat).

我还看到了一些我无法使用的 eval 解决方案(除了被指出为安全威胁之外)。

Is there really no way to do it in an elegant way?

真的没有办法以优雅的方式做到这一点吗?

Similar question with no real answer:
How to parse ASP.NET JSON Date format with GWT

没有真正答案的类似问题:
How to parse ASP.NET JSON Date format with GWT

采纳答案by Jacob

There is no standard JSON representation of dates. You should do what @jAndy suggested and not serialize a DateTimeat all; just send an RFC 1123 date string ToString("r")or a seconds-from-Unix-epoch number, or something else that you can use in the JavaScript to construct a Date.

日期没有标准的 JSON 表示。您应该按照@jAndy 的建议进行操作,而根本不要序列化 ​​a DateTime;只需发送一个 RFC 1123 日期字符串ToString("r")或一个来自 Unix-epoch 的秒数,或者你可以在 JavaScript 中使用的其他东西来构造一个Date.

回答by Tim

The JSON.parsefunction accepts an optional DateTime reviver function. You can use a function like this:

JSON.parse函数接受一个可选的 DateTime reviver 函数。您可以使用这样的函数:

dateTimeReviver = function (key, value) {
    var a;
    if (typeof value === 'string') {
        a = /\/Date\((\d*)\)\//.exec(value);
        if (a) {
            return new Date(+a[1]);
        }
    }
    return value;
}

Then call

然后打电话

JSON.parse(somejsonstring, dateTimeReviver);

And your dates will come out right.

你的日期会出来的。

回答by treeface

This answer from Roy Tinker here:

来自Roy Tinker 的这个回答:

var date = new Date(parseInt(jsonDate.substr(6)));

As he says: The substr function takes out the "/Date(" part, and the parseInt function gets the integer and ignores the ")/" at the end. The resulting number is passed into the Date constructor.

正如他所说:substr 函数取出“/Date(”部分,parseInt 函数获取整数并忽略末尾的“)/”。结果数字被传递到 Date 构造函数中。

Another option is to simply format your information properly on the ASP side such that JavaScript can easily read it. Consider doing this for your dates:

另一种选择是简单地在 ASP 端正确格式化您的信息,以便 JavaScript 可以轻松读取它。考虑为您的日期执行此操作:

DateTime.Now()

Which should return a format like this:

应该返回这样的格式:

7/22/2008 12:11:04 PM

If you pass this into a JavaScript Dateconstructor like this:

如果您将其传递给这样的 JavaScriptDate构造函数:

var date = new Date('7/22/2008 12:11:04 PM');

The variable datenow holds this value:

变量date现在持有这个值:

Tue Jul 22 2008 12:11:04 GMT-0700 (Pacific Daylight Time)

Naturally, you can format this DateTimeobject into whatever sort of string/int the JS Dateconstructor accepts.

当然,您可以将此DateTime对象格式化为 JSDate构造函数接受的任何类型的 string/int 。

回答by LeeGee

if you use the JavaScript style ISO8601 date in JSON, you could use this, from MDN

如果您在 JSON 中使用 JavaScript 样式 ISO8601 日期,则可以使用它,来自MDN

var jsonDate = (new Date()).toJSON();
var backToDate = new Date(jsonDate);
console.log(jsonDate); //2015-10-26T07:46:36.611Z

回答by ViPuL5

You can convert JSON Date to normal date format in JavaScript.

您可以在 JavaScript 中将 JSON 日期转换为普通日期格式。

var date = new Date(parseInt(jsonDate.substr(6)));

回答by Psytronic

What's wrong with:

有什么问题:

new Date(1293034567877);

This returns for me "Wed Dec 22 2010 16:16:07 GMT+0000 (GMT Standard Time)".

这对我来说是“2010 年 12 月 22 日星期三 16:16:07 GMT+0000(GMT 标准时间)”。

Or do you need to get the number out the json?

或者你需要从json中取出数字吗?

回答by Eman

I know this is a very old thread but I wish to post this to help those who bump into this like I did.

我知道这是一个非常古老的线程,但我希望发布它来帮助那些像我一样遇到这个问题的人。

if you don't care about using a 3rd party script, you can use moment,jsThen you can use .format() to format it to anything you want it to.

如果您不关心使用 3rd 方脚本,您可以使用moment,js然后您可以使用 .format() 将其格式化为您想要的任何内容。

回答by Gabriel Andrés Brancolini

Dates are always a nightmare. Answering your old question, perhaps this is the most elegant way:

约会总是一场噩梦。回答你的老问题,也许这是最优雅的方式:

eval(("new " + "/Date(1455418800000)/").replace(/\//g,""))

With eval we convert our string to javascript code. Then we remove the "/", into the replace function is a regular expression. As we start with new then our sentences will excecute this:

使用 eval 我们将字符串转换为 javascript 代码。然后我们去掉“/”,进入replace函数就是一个正则表达式。当我们从 new 开始时,我们的句子将执行:

new Date(1455418800000)

Now, one thing I started using long time ago, is long values that are represented in ticks... why? well, localization and stop thinking in how is date configured in every server or every client. In fact, I use it too in databases.

现在,我很久以前开始使用的一件事是用刻度表示的长值......为什么?好吧,本地化并停止思考如何在每个服务器或每个客户端中配置日期。事实上,我也在数据库中使用它。

Perhaps is quite late for this answer, but can help anybody arround here.

也许这个答案已经很晚了,但可以帮助这里的任何人。

回答by Rosdi Kasim

AngularJS couldn't parse .NET JSON date /Date(xxxxxxxxxxxxx)/string either..

AngularJS 也无法解析 .NET JSON 日期/Date(xxxxxxxxxxxxx)/字符串..

I side stepped this issue by formatting the date to its ISO 8601 string representation instead of dumping the Dateobject directly...

我通过将日期格式化为其 ISO 8601 字符串表示而不是Date直接转储对象来解决这个问题......

Here is a sample of ASP.NET MVC code..

这是 ASP.NET MVC 代码的示例..

return Json(new { 
  date : DateTime.Now.ToString("O") //ISO 8601 Angular understands this format
});

I tried RFC 1123but it doesn't work.. Angular treats this as string instead of Date.

我试过了,RFC 1123但它不起作用.. Angular 将其视为字符串而不是日期。

return Json(new { 
  date : DateTime.Now.ToString("R") //RFC 1123 Angular won't parse this
});

回答by onixpam

As Callum mentioned, for me, the best way is to change the Controller method to string instead of JsonResult".

正如 Callum 所提到的,对我来说,最好的方法是将 Controller 方法更改为字符串而不是 JsonResult”。

public string GetValues()
{
  MyObject.DateFrom = DateTime.Now;
  return JsonConvert.SerializeObject(MyObject);
}

From the ajax method you can do something like this

从 ajax 方法你可以做这样的事情

 $.ajax({
 url: "/MyController/GetValues",
 type: "post",
 success: function (data) {
 var validData = JSON.parse(data);
//if you are using datepicker and you want set a format
$("#DateFrom").val($.datepicker.formatDate("dd/mm/yy", new Date(validData.DateFrom)));                                      
// if you want the date as returned
$("#DateFrom").val(new Date(validData.DateFrom))
}
});