jQuery 如何格式化 Microsoft JSON 日期?

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

How do I format a Microsoft JSON date?

jqueryasp.netajaxjson

提问by Mark Struzinski

I'm taking my first crack at Ajaxwith jQuery. I'm getting my data onto my page, but I'm having some trouble with the JSON data that is returned for Date data types. Basically, I'm getting a string back that looks like this:

我正在使用 jQuery对Ajax进行第一次尝试。我正在将我的数据放到我的页面上,但是我在处理为 Date 数据类型返回的 JSON 数据时遇到了一些问题。基本上,我得到了一个看起来像这样的字符串:

/Date(1224043200000)/

From someone totally new to JSON - How do I format this to a short date format? Should this be handled somewhere in the jQuery code? I've tried the jQuery.UI.datepickerplugin using $.datepicker.formatDate()without any success.

从一个完全不熟悉 JSON 的人 - 如何将其格式化为短日期格式?这应该在 jQuery 代码的某个地方处理吗?我试过使用jQuery.UI.datepicker插件$.datepicker.formatDate()没有任何成功。

FYI: Here's the solution I came up with using a combination of the answers here:

仅供参考:这是我使用此处的答案组合提出的解决方案:

function getMismatch(id) {
  $.getJSON("Main.aspx?Callback=GetMismatch",
    { MismatchId: id },

    function (result) {
      $("#AuthMerchId").text(result.AuthorizationMerchantId);
      $("#SttlMerchId").text(result.SettlementMerchantId);
      $("#CreateDate").text(formatJSONDate(Date(result.AppendDts)));
      $("#ExpireDate").text(formatJSONDate(Date(result.ExpiresDts)));
      $("#LastUpdate").text(formatJSONDate(Date(result.LastUpdateDts)));
      $("#LastUpdatedBy").text(result.LastUpdateNt);
      $("#ProcessIn").text(result.ProcessIn);
    }
  );

  return false;
}

function formatJSONDate(jsonDate) {
  var newDate = dateFormat(jsonDate, "mm/dd/yyyy");
  return newDate;
}

This solution got my object from the callback method and displayed the dates on the page properly using the date format library.

此解决方案从回调方法中获取我的对象,并使用日期格式库在页面上正确显示日期。

采纳答案by Roy Tinker

eval()is not necessary. This will work fine:

eval()没有必要。这将正常工作:

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

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 Dateconstructor.

substr()函数取出/Date(一部分,并且parseInt()功能得到整数,而忽略了)/底。结果数字被传递给Date构造函数。



I have intentionally left out the radix (the 2nd argument to parseInt); see my comment below.

我故意省略了基数( 的第二个参数parseInt);请参阅下面的评论

Also, I completely agree with Rory's comment: ISO-8601 dates are preferred over this old format - so this format generally shouldn't be used for new development. See the excellent Json.NETlibrary for a great alternative that serializes dates using the ISO-8601 format.

另外,我完全同意Rory 的评论:ISO-8601 日期比这种旧格式更受欢迎 - 所以这种格式通常不应该用于新的开发。请参阅优秀的Json.NET库,了解使用 ISO-8601 格式序列化日期的绝佳替代方案。

For ISO-8601 formatted JSON dates, just pass the string into the Dateconstructor:

对于 ISO-8601 格式的 JSON 日期,只需将字符串传递给Date构造函数:

var date = new Date(jsonDate); //no ugly parsing needed; full timezone support

回答by Panos

You can use this to get a date from JSON:

您可以使用它从 JSON 获取日期:

var date = eval(jsonDate.replace(/\/Date\((\d+)\)\//gi, "new Date()"));

And then you can use a JavaScript Date Formatscript (1.2 KB when minified and gzipped) to display it as you want.

然后您可以使用JavaScript 日期格式脚本(缩小和压缩时为 1.2 KB)根据需要显示它。

回答by Jason Jong

For those using Newtonsoft Json.NET, read up on how to do it via Native JSON in IE8, Firefox 3.5 plus Json.NET.

对于那些使用 Newtonsoft Json.NET 的人,请阅读如何通过IE8、Firefox 3.5 和 Json.NET 中的 Native JSON来实现。

Also the documentation on changing the format of dates written by Json.NET is useful: Serializing Dates with Json.NET

此外,有关更改 Json.NET 编写的日期格式的文档也很有用: Serializing Dates with Json.NET

For those that are too lazy, here are the quick steps. As JSON has a loose DateTime implementation, you need to use the IsoDateTimeConverter(). Note that since Json.NET 4.5 the default date format is ISO so the code below isn't needed.

对于那些太懒的人,这里是快速步骤。由于 JSON 具有松散的 DateTime 实现,因此您需要使用IsoDateTimeConverter(). 请注意,从 Json.NET 4.5 开始,默认日期格式为 ISO,因此不需要下面的代码。

string jsonText = JsonConvert.SerializeObject(p, new IsoDateTimeConverter());

The JSON will come through as

JSON 将通过

"fieldName": "2009-04-12T20:44:55"

Finally, some JavaScript to convert the ISO date to a JavaScript date:

最后,一些 JavaScript 将 ISO 日期转换为 JavaScript 日期:

function isoDateReviver(value) {
  if (typeof value === 'string') {
    var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(?:([\+-])(\d{2})\:(\d{2}))?Z?$/.exec(value);
      if (a) {
        var utcMilliseconds = Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]);
        return new Date(utcMilliseconds);
      }
  }
  return value;
}

I used it like this

我是这样用的

$("<span />").text(isoDateReviver(item.fieldName).toLocaleString()).appendTo("#" + divName);

回答by Aaron

The original example:

原始示例:

/Date(1224043200000)/  

does not reflect the formatting used by WCF when sending dates via WCF REST using the built-in JSON serialization. (at least on .NET 3.5, SP1)

使用内置 JSON 序列化通过 WCF REST 发送日期时,不反映 WCF 使用的格式。(至少在 .NET 3.5,SP1 上)

I found the answer here helpful, but a slight edit to the regex is required, as it appears that the timezone GMT offset is being appended onto the number returned (since 1970) in WCF JSON.

我发现这里的答案很有帮助,但需要对正则表达式进行轻微编辑,因为似乎时区 GMT 偏移量被附加到 WCF JSON 中返回的数字(自 1970 年以来)。

In a WCF service I have:

在 WCF 服务中,我有:

[OperationContract]
[WebInvoke(
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.WrappedRequest
    )]
ApptVisitLinkInfo GetCurrentLinkInfo( int appointmentsId );

ApptVisitLinkInfo is defined simply:

ApptVisitLinkInfo 的定义很简单:

public class ApptVisitLinkInfo {
    string Field1 { get; set; }
    DateTime Field2 { get; set; }
    ...
}

When "Field2" is returned as Json from the service the value is:

当“Field2”作为 Json 从服务返回时,值为:

/Date(1224043200000-0600)/

Notice the timezone offset included as part of the value.

请注意作为值的一部分包含的时区偏移量。

The modified regex:

修改后的正则表达式:

/\/Date\((.*?)\)\//gi

It's slightly more eager and grabs everything between the parens, not just the first number. The resulting time sinze 1970, plus timezone offset can all be fed into the eval to get a date object.

它稍微更急切并抓住括号之间的所有内容,而不仅仅是第一个数字。结果时间为 1970 年,加上时区偏移量都可以输入到 eval 中以获取日期对象。

The resulting line of JavaScript for the replace is:

用于替换的 JavaScript 代码行是:

replace(/\/Date\((.*?)\)\//gi, "new Date()");

回答by Robert Koritnik

Don't repeat yourself - automate date conversion using $.parseJSON()

不要重复自己 - 使用自动日期转换 $.parseJSON()

Answers to your post provide manual date conversion to JavaScript dates. I've extended jQuery's $.parseJSON()just a little bit, so it's able to automatically parse dates when you instruct it to. It processes ASP.NET formatted dates (/Date(12348721342)/) as well as ISO formatted dates (2010-01-01T12.34.56.789Z) that are supported by native JSON functions in browsers (and libraries like json2.js).

对您帖子的回答提供了到 JavaScript 日期的手动日期转换。我对 jQuery 进行$.parseJSON()了一点扩展,因此它能够在您指示时自动解析日期。它处理 ASP.NET 格式的日期 ( /Date(12348721342)/) 以及2010-01-01T12.34.56.789Z浏览器中原生 JSON 函数(以及 json2.js 等库)支持的ISO 格式的日期 ( )。

Anyway. If you don't want to repeat your date conversion code over and over again I suggest you read this blog postand get the code that will make your life a little easier.

反正。如果你不想一遍又一遍地重复你的日期转换代码,我建议你阅读这篇博文并获得能让你的生活更轻松的代码。

回答by John Boker

If you say in JavaScript,

如果你用 JavaScript 说,

var thedate = new Date(1224043200000);
alert(thedate);

you will see that it's the correct date, and you can use that anywhere in JavaScript code with any framework.

您将看到它是正确的日期,并且您可以在任何框架的 JavaScript 代码中的任何位置使用它。

回答by John Boker

Click here to check the Demo

单击此处查看演示

JavaScript/jQuery

JavaScript/jQuery

var = MyDate_String_Value = "/Date(1224043200000)/"
var value = new Date
            (
                 parseInt(MyDate_String_Value.replace(/(^.*\()|([+-].*$)/g, ''))
            );
var dat = value.getMonth() +
                         1 +
                       "/" +
           value.getDate() +
                       "/" +
       value.getFullYear();

Result- "10/15/2008"

结果- “10/15/2008”

回答by Chris Moschini

Updated

更新

We have an internal UI library that has to cope with both Microsoft's ASP.NET built-in JSON format, like /Date(msecs)/, asked about here originally, and most JSON's date format including JSON.NET's, like 2014-06-22T00:00:00.0. In addition we need to cope with oldIE's inability to cope with anything but 3 decimal places.

我们有一个内部 UI 库,它必须同时处理 Microsoft 的 ASP.NET 内置 JSON 格式,例如/Date(msecs)/, 最初在这里询问,以及大多数 JSON 的日期格式,包括 JSON.NET 的,例如2014-06-22T00:00:00.0. 此外,我们还需要解决oldIE 无法处理小数点后 3 位以外的任何内容的问题

We first detect what kind of date we're consuming, parse it into a normal JavaScript Dateobject, then format that out.

我们首先检测我们正在消费的日期类型,将其解析为一个普通的 JavaScriptDate对象,然后将其格式化。

1) Detect Microsoft Date format

1) 检测微软日期格式

// Handling of Microsoft AJAX Dates, formatted like '/Date(01238329348239)/'
function looksLikeMSDate(s) {
    return /^\/Date\(/.test(s);
}

2) Detect ISO date format

2)检测ISO日期格式

var isoDateRegex = /^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(\.\d\d?\d?)?([\+-]\d\d:\d\d|Z)?$/;

function looksLikeIsoDate(s) {
    return isoDateRegex.test(s);
}

3) Parse MS date format:

3)解析MS日期格式:

function parseMSDate(s) {
    // Jump forward past the /Date(, parseInt handles the rest
    return new Date(parseInt(s.substr(6)));
}

4) Parse ISO date format.

4) 解析 ISO 日期格式。

We do at least have a way to be sure that we're dealing with standard ISO dates or ISO dates modified to always have three millisecond places (see above), so the code is different depending on the environment.

我们至少有办法确保我们处理的是标准 ISO 日期或 ISO 日期修改为始终具有三毫秒位置(见上文),因此代码因环境而异。

4a) Parse standard ISO Date format, cope with oldIE's issues:

4a) 解析标准ISO日期格式,解决oldIE的问题:

function parseIsoDate(s) {
    var m = isoDateRegex.exec(s);

    // Is this UTC, offset, or undefined? Treat undefined as UTC.
    if (m.length == 7 ||                // Just the y-m-dTh:m:s, no ms, no tz offset - assume UTC
        (m.length > 7 && (
            !m[7] ||                    // Array came back length 9 with undefined for 7 and 8
            m[7].charAt(0) != '.' ||    // ms portion, no tz offset, or no ms portion, Z
            !m[8] ||                    // ms portion, no tz offset
            m[8] == 'Z'))) {            // ms portion and Z
        // JavaScript's weirdo date handling expects just the months to be 0-based, as in 0-11, not 1-12 - the rest are as you expect in dates.
        var d = new Date(Date.UTC(m[1], m[2]-1, m[3], m[4], m[5], m[6]));
    } else {
        // local
        var d = new Date(m[1], m[2]-1, m[3], m[4], m[5], m[6]);
    }

    return d;
}

4b) Parse ISO format with a fixed three millisecond decimal places - much easier:

4b) 使用固定的三毫秒小数位解析 ISO 格式 - 更容易:

function parseIsoDate(s) {
    return new Date(s);
}

5) Format it:

5)格式化:

function hasTime(d) {
    return !!(d.getUTCHours() || d.getUTCMinutes() || d.getUTCSeconds());
}

function zeroFill(n) {
    if ((n + '').length == 1)
        return '0' + n;

    return n;
}

function formatDate(d) {
    if (hasTime(d)) {
        var s = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
        s += ' ' + d.getHours() + ':' + zeroFill(d.getMinutes()) + ':' + zeroFill(d.getSeconds());
    } else {
        var s = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
    }

    return s;
}

6) Tie it all together:

6)把它们绑在一起:

function parseDate(s) {
    var d;
    if (looksLikeMSDate(s))
        d = parseMSDate(s);
    else if (looksLikeIsoDate(s))
        d = parseIsoDate(s);
    else
        return null;

    return formatDate(d);
}

The below old answer is useful for tying this date formatting into jQuery's own JSON parsing so you get Date objects instead of strings, or if you're still stuck in jQuery <1.5 somehow.

下面的旧答案可用于将此日期格式绑定到 jQuery 自己的 JSON 解析中,以便您获得 Date 对象而不是字符串,或者如果您仍然以某种方式卡在 jQuery <1.5 中。

Old Answer

旧答案

If you're using jQuery 1.4's Ajax function with ASP.NET MVC, you can turn all DateTime properties into Date objects with:

如果您在 ASP.NET MVC 中使用 jQuery 1.4 的 Ajax 函数,您可以使用以下命令将所有 DateTime 属性转换为 Date 对象:

// Once
jQuery.parseJSON = function(d) {return eval('(' + d + ')');};

$.ajax({
    ...
    dataFilter: function(d) {
        return d.replace(/"\\/(Date\(-?\d+\))\\/"/g, 'new ');
    },
    ...
});

In jQuery 1.5 you can avoid overriding the parseJSONmethod globally by using the converters option in the Ajax call.

在 jQuery 1.5 中,您可以parseJSON通过在 Ajax 调用中使用转换器选项来避免全局覆盖该方法。

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/jQuery.ajax/

Unfortunately you have to switch to the older eval route in order to get Dates to parse globally in-place - otherwise you need to convert them on a more case-by-case basis post-parse.

不幸的是,您必须切换到较旧的 eval 路由才能使日期在全局就地解析 - 否则您需要在解析后逐案转换它们。

回答by johnstok

There is no built in date type in JSON. This looks like the number of seconds / milliseconds from some epoch. If you know the epoch you can create the date by adding on the right amount of time.

JSON 中没有内置日期类型。这看起来像是某个时代的秒数/毫秒数。如果您知道纪元,则可以通过添加适当的时间来创建日期。

回答by Venemo

I also had to search for a solution to this problem and eventually I came across moment.js which is a nice library that can parse this date format and many more.

我还不得不寻找这个问题的解决方案,最终我遇到了 moment.js,这是一个很好的库,可以解析这种日期格式等等。

var d = moment(yourdatestring)

It saved some headache for me so I thought I'd share it with you. :)
You can find some more info about it here: http://momentjs.com/

它为我节省了一些头痛,所以我想我会和你分享。:)
你可以在这里找到更多的信息:http: //momentjs.com/