如何格式化Microsoft JSON日期?

时间:2008-10-15 20:43:41

标签: jquery asp.net ajax json

我正在使用jQuery在Ajax处进行第一次破解。我将数据放到我的页面上,但是我在为Date数据类型返回的JSON数据方面遇到了一些麻烦。基本上,我得到的字符串看起来像这样:

/Date(1224043200000)/

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

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

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;
}

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

40 个答案:

答案 0 :(得分:1639)

eval()没有必要。这样可以正常工作:

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

substr()函数取出/Date(部分,parseInt()函数获取整数,并忽略最后的)/。生成的数字将传递到Date构造函数。


我故意遗漏了基数(parseInt的第二个参数);见my comment below

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

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

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

答案 1 :(得分:124)

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

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

然后你可以使用a JavaScript Date Format脚本(缩小和gzip时为1.2 KB)来显示它。

答案 2 :(得分:93)

对于使用Newtonsoft Json.NET的用户,请通过 Native JSON in IE8, Firefox 3.5 plus Json.NET 了解如何操作。

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

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

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

JSON将以

的形式出现
"fieldName": "2009-04-12T20:44:55"

最后,一些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;
}

我像这样使用它

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

答案 3 :(得分:63)

原始示例:

/Date(1224043200000)/  

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

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

在WCF服务中,我有:

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

ApptVisitLinkInfo的定义很简单:

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

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

/Date(1224043200000-0600)/

请注意时区偏移包含在值中。

修改后的正则表达式:

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

它更加急切,抓住了parens之间的一切,而不仅仅是第一个数字。产生的时间是1970年,加上时区偏移可以全部输入到eval中以获得日期对象。

替换的JavaScript结果是:

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

答案 4 :(得分:60)

不要重复自己 - 使用$.parseJSON()

自动化日期转换

您帖子的答案提供了手动日期转换为JavaScript日期。我只是稍微扩展了jQuery的$.parseJSON(),因此它可以在你指示日期时自动解析日期。它处理ASP.NET格式化日期(/Date(12348721342)/)以及ISO格式化日期(2010-01-01T12.34.56.789Z),这些日期由浏览器(以及json2.js等库)中的本机JSON函数支持。

反正。如果您不想一遍又一遍地重复日期转换代码,建议您阅读this blog post并获取能让您的生活更轻松的代码。

答案 5 :(得分:59)

如果你在JavaScript中说,

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

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

答案 6 :(得分:55)

Click here to check the Demo

的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();

结果 - “10/15/2008”

答案 7 :(得分:36)

更新

我们有一个内部UI库,它必须处理Microsoft的ASP.NET内置JSON格式,如/Date(msecs)/,最初询问,以及大多数JSON的日期格式,包括JSON.NET,如{{ 1}}。此外,我们需要应对oldIE's inability to cope with anything but 3 decimal places

我们首先检测我们正在使用哪种日期,将其解析为普通的JavaScript 2014-06-22T00:00:00.0对象,然后将其格式化。

1)检测Microsoft日期格式

Date

2)检测ISO日期格式

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

3)解析MS日期格式:

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

4)解析ISO日期格式。

我们至少有办法确保我们处理的标准ISO日期或ISO日期被修改为总是有三毫秒的位置(see above),因此代码根据环境而有所不同。

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

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

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

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;
}

5)格式化:

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

6)将它们捆绑在一起:

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;
}

以下旧答案对于将此日期格式绑定到jQuery自己的JSON解析非常有用,因此您可以获取Date对象而不是字符串,或者如果您仍然停留在jQuery&lt; 1.5中。

旧答案

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

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

    return formatDate(d);
}

在jQuery 1.5中,您可以通过使用Ajax调用中的converter选项来避免全局覆盖// Once jQuery.parseJSON = function(d) {return eval('(' + d + ')');}; $.ajax({ ... dataFilter: function(d) { return d.replace(/"\\\/(Date\(-?\d+\))\\\/"/g, 'new $1'); }, ... }); 方法。

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

不幸的是,您必须切换到较旧的eval路由才能使Dates在全局内进行解析 - 否则您需要在解析后逐个转换它们。

答案 8 :(得分:24)

我还必须搜索这个问题的解决方案,最后我遇到了moment.js这是一个很好的库,可以解析这个日期格式等等。

var d = moment(yourdatestring)

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

答案 9 :(得分:23)

我最终将“字符添加到Panos的正则表达式中,以摆脱Microsoft序列化程序在将对象写入内联脚本时生成的字符:

因此,如果你的C#code-behind中有一个类似

的属性
protected string JsonObject { get { return jsSerialiser.Serialize(_myObject); }}

在你的aspx中你有

<script type="text/javascript">
    var myObject = '<%= JsonObject %>';
</script>

你会得到像

这样的东西
var myObject = '{"StartDate":"\/Date(1255131630400)\/"}';

注意双引号。

为了将其转换为eval将正确反序列化的形式,我使用了:

myObject = myObject.replace(/"\/Date\((\d+)\)\/"/g, 'new Date($1)');

我使用Prototype并使用它添加了

String.prototype.evalJSONWithDates = function() {
    var jsonWithDates = this.replace(/"\/Date\((\d+)\)\/"/g, 'new Date($1)');
    return jsonWithDates.evalJSON(true);
}

答案 10 :(得分:23)

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

答案 11 :(得分:21)

在jQuery 1.5中,只要您有json2.js来覆盖旧浏览器,就可以按如下方式反序列化来自Ajax的所有日期:

(function () {
    var DATE_START = "/Date(";
    var DATE_START_LENGTH = DATE_START.length;

    function isDateString(x) {
        return typeof x === "string" && x.startsWith(DATE_START);
    }

    function deserializeDateString(dateString) {
        var dateOffsetByLocalTime = new Date(parseInt(dateString.substr(DATE_START_LENGTH)));
        var utcDate = new Date(dateOffsetByLocalTime.getTime() - dateOffsetByLocalTime.getTimezoneOffset() * 60 * 1000);
        return utcDate;
    }

    function convertJSONDates(key, value) {
      if (isDateString(value)) {
        return deserializeDateString(value);
      }
      return value;
    }

    window.jQuery.ajaxSetup({
      converters: {
        "text json": function(data) {
          return window.JSON.parse(data, convertJSONDates);
        }
      }
    });
}());

我包含的逻辑假定您从服务器发送所有日期为UTC(您应该);然后,使用者获得一个JavaScript Date对象,该对象具有正确的ticks值以反映这一点。也就是说,在日期调用getUTCHours()等将返回与在服务器上相同的值,并且调用getHours()将返回用户的本地时区中由浏览器确定的值。 / p>

这不会考虑带有时区偏移的WCF格式,但这会相对容易添加。

答案 12 :(得分:19)

使用jQuery UI datepicker - 只有在你已经包含jQuery UI时才真正有意义:

$.datepicker.formatDate('MM d, yy', new Date(parseInt('/Date(1224043200000)/'.substr(6)))); 

输出:

  

2008年10月15日

答案 13 :(得分:19)

不要过度思考这一点。就像我们已经做了几十年一样,从1970年1月1日格林威治标准时间/ UTC /时间的事实上的标准时期传递一个数字偏移量,从这个时代开始的秒数(或毫秒)。 JavaScript喜欢它,Java喜欢它,C喜欢它,而互联网喜欢它。

答案 14 :(得分:18)

这些答案中的每一个都有一个共同点:它们都将日期存储为单个值(通常是字符串)。

另一个选择是利用JSON的固有结构,并将日期表示为数字列表:

{ "name":"Nick",
  "birthdate":[1968,6,9] }

当然,你必须确保对话的两端都同意格式(年,月,日),以及哪些字段是日期,......但它的优点是完全避免日期到字符串转换的问题。这都是数字 - 根本没有字符串。此外,使用订单:年,月,日也允许按日期进行适当的排序。

只需在框外思考 - JSON日期不必存储为字符串。

这样做的另一个好处是,您可以通过CouchDB处理数组值查询的方式,轻松(并有效)选择给定年份或月份的所有记录。

答案 15 :(得分:16)

以精彩的帖子发帖:

var d = new Date(parseInt('/Date(1224043200000)/'.slice(6, -2)));
alert('' + (1 + d.getMonth()) + '/' + d.getDate() + '/' + d.getFullYear().toString().slice(-2));

答案 16 :(得分:16)

var newDate = dateFormat(jsonDate, "mm/dd/yyyy"); 

是否有其他选项没有使用jQuery库?

答案 17 :(得分:15)

只是为了在这里添加另一种方法,WCF所采用的“滴答方法”如果你不是非常小心,如描述here和其他地方,就会出现时区问题。所以我现在使用的是.NET 8和ISO 8601格式。 JavaScript正式支持包括时区偏移。以下是详细信息:

在WCF / .NET中:

其中CreationDate是System.DateTime; ToString(“o”)使用.NET Round-trip format specifier生成符合ISO 8601标准的日期字符串

new MyInfo {
    CreationDate = r.CreationDate.ToString("o"),
};

在JavaScript中

在检索JSON之后,我使用Date构造函数来修复日期为JavaSript Date对象,该构造函数接受ISO 8601日期字符串...

$.getJSON(
    "MyRestService.svc/myinfo",
    function (data) {
        $.each(data.myinfos, function (r) {
            this.CreatedOn = new Date(this.CreationDate);
        });
        // Now each myinfo object in the myinfos collection has a CreatedOn field that is a real JavaScript date (with timezone intact).
       alert(data.myinfos[0].CreationDate.toLocaleString());
    }
)

拥有JavaScript日期后,您可以使用所有方便可靠的日期方法,例如toDateStringtoLocaleString等。

答案 18 :(得分:9)

我得到这样的日期:

"/Date(1276290000000+0300)/"

在某些示例中,日期的格式略有不同:

"/Date(12762900000000300)/"
"Date(1276290000000-0300)"

所以我提出了以下RegExp:

/\/+Date\(([\d+]+)\)\/+/

,最终代码为:

var myDate = new Date(parseInt(jsonWcfDate.replace(/\/+Date\(([\d+-]+)\)\/+/, '$1')));

希望它有所帮助。

更新: 我从微软找到了这个链接: How do I Serialize Dates with JSON?

这似乎是我们都在寻找的。

答案 19 :(得分:9)

以下是解析JSON日期的非常简单的解决方案。根据您的要求使用以下功能。您只需将JSON格式作为参数提取的日期传递给以下函数:

function JSONDate(dateStr) {
    var m, day;
    jsonDate = dateStr;
    var d = new Date(parseInt(jsonDate.substr(6)));
    m = d.getMonth() + 1;
    if (m < 10)
        m = '0' + m
    if (d.getDate() < 10)
        day = '0' + d.getDate()
    else
        day = d.getDate();
    return (m + '/' + day + '/' + d.getFullYear())
}

function JSONDateWithTime(dateStr) {
    jsonDate = dateStr;
    var d = new Date(parseInt(jsonDate.substr(6)));
    var m, day;
    m = d.getMonth() + 1;
    if (m < 10)
        m = '0' + m
    if (d.getDate() < 10)
        day = '0' + d.getDate()
    else
        day = d.getDate();
    var formattedDate = m + "/" + day + "/" + d.getFullYear();
    var hours = (d.getHours() < 10) ? "0" + d.getHours() : d.getHours();
    var minutes = (d.getMinutes() < 10) ? "0" + d.getMinutes() : d.getMinutes();
    var formattedTime = hours + ":" + minutes + ":" + d.getSeconds();
    formattedDate = formattedDate + " " + formattedTime;
    return formattedDate;
}

答案 20 :(得分:9)

var obj = eval('(' + "{Date: \/Date(1278903921551)\/}".replace(/\/Date\((\d+)\)\//gi, "new Date($1)") + ')');
var dateValue = obj["Date"];

答案 21 :(得分:8)

这令人沮丧。我的解决方案是从ASP.NET的JavaScriptSerializer生成的值中解析出“/和/”,这样虽然JSON可能没有日期文字,但它仍然被浏览器解释为日期,这就是我真正的所有想:{"myDate":Date(123456789)}

Custom JavaScriptConverter for DateTime?

我必须强调Roy Tinker评论的准确性。这不是合法的JSON。在服务器成为JavaScript问题之前,删除问题是服务器上的一个肮脏,肮脏的黑客。它会阻塞JSON解析器。我用它来起飞,但我不再使用它了。但是,我仍然觉得最好的答案在于改变服务器格式化日期的方式,例如,如其他地方提到的ISO。

答案 22 :(得分:8)

您还可以使用JavaScript库moment.js,当您计划处理不同的本地化格式并使用日期值执行其他操作时,它会派上用场:

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

    function (result) {
        $("#AuthMerchId").text(result.AuthorizationMerchantId);
        $("#SttlMerchId").text(result.SettlementMerchantId);
        $("#CreateDate").text(moment(result.AppendDts).format("L"));
        $("#ExpireDate").text(moment(result.ExpiresDts).format("L"));
        $("#LastUpdate").text(moment(result.LastUpdateDts).format("L"));
        $("#LastUpdatedBy").text(result.LastUpdateNt);
        $("#ProcessIn").text(result.ProcessIn);
    }
    );
    return false;
}

设置本地化就像在项目中添加配置文件(在momentjs.com上获取)和配置语言一样简单:

moment.lang('de');

答案 23 :(得分:8)

检查日期ISO标准;有点像这样:

yyyy.MM.ddThh:mm

变为2008.11.20T22:18

答案 24 :(得分:8)

在您的页面中添加jQuery UI插件:

function DateFormate(dateConvert) {
    return $.datepicker.formatDate("dd/MM/yyyy", eval('new ' + dateConvert.slice(1, -1)));
};

答案 25 :(得分:7)

迟到的帖子,但对于搜索此帖子的人来说。

想象一下:

    [Authorize(Roles = "Administrator")]
    [Authorize(Roles = "Director")]
    [Authorize(Roles = "Human Resources")]
    [HttpGet]
    public ActionResult GetUserData(string UserIdGuidKey)
    {
        if (UserIdGuidKey!= null)
        {
            var guidUserId = new Guid(UserIdGuidKey);
            var memuser = Membership.GetUser(guidUserId);
            var profileuser = Profile.GetUserProfile(memuser.UserName);
            var list = new {
                              UserName = memuser.UserName,
                              Email = memuser.Email ,
                              IsApproved = memuser.IsApproved.ToString() ,
                              IsLockedOut = memuser.IsLockedOut.ToString() ,
                              LastLockoutDate = memuser.LastLockoutDate.ToString() ,
                              CreationDate = memuser.CreationDate.ToString() ,
                              LastLoginDate = memuser.LastLoginDate.ToString() ,
                              LastActivityDate = memuser.LastActivityDate.ToString() ,
                              LastPasswordChangedDate = memuser.LastPasswordChangedDate.ToString() ,
                              IsOnline = memuser.IsOnline.ToString() ,
                              FirstName = profileuser.FirstName ,
                              LastName = profileuser.LastName ,
                              NickName = profileuser.NickName ,
                              BirthDate = profileuser.BirthDate.ToString() ,
            };
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        return Redirect("Index");
    }

正如您所看到的,我正在利用C#3.0的功能来创建“Auto”Generics。它有点懒,但我喜欢它并且它有效。 请注意:Profile是我为我的Web应用程序项目创建的自定义类。

答案 26 :(得分:7)

答案 27 :(得分:7)

这也可以帮到你。

 function ToJavaScriptDate(value) { //To Parse Date from the Returned Parsed Date
        var pattern = /Date\(([^)]+)\)/;
        var results = pattern.exec(value);
        var dt = new Date(parseFloat(results[1]));
        return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
    }

答案 28 :(得分:6)

仅供参考,对于在服务器端使用Python的任何人:datetime.datetime()。ctime()返回一个可由“new Date()”本机解析的字符串。也就是说,如果您创建一个新的datetime.datetime实例(例如使用datetime.datetime.now),则该字符串可以包含在JSON字符串中,然后该字符串可以作为第一个参数传递给Date构造函数。我还没有发现任何例外情况,但我也没有过于严格地测试它。

答案 29 :(得分:6)

如果.NET返回...

,该怎么办?
return DateTime.Now.ToString("u"); //"2013-09-17 15:18:53Z"

然后在JavaScript中......

var x = new Date("2013-09-17 15:18:53Z");

答案 30 :(得分:5)

在以下代码中。我有

1。从日期字符串中检索时间戳。

2。并将其解析为Int

3。最后使用它创建了Date

&#13;
&#13;
var dateString = "/Date(1224043200000)/";
var seconds = parseInt(dateString.replace(/\/Date\(([0-9]+)[^+]\//i, "$1"));
var date = new Date(seconds);
console.log(date);
&#13;
&#13;
&#13;

答案 31 :(得分:2)

作为旁注,KendoUI支持转换Microsoft JSON日期。 因此,如果您的项目引用了“KendoUI”,则可以使用

var newDate = kendo.parseDate(jsonDate);

答案 32 :(得分:2)

这使用regular expression,它也有效:

var date = new Date(parseInt(/^\/Date\((.*?)\)\/$/.exec(jsonDate)[1], 10));

答案 33 :(得分:2)

您可以尝试使用的另一个正则表达式示例:

var mydate = json.date
var date = new Date(parseInt(mydate.replace(/\/Date\((-?\d+)\)\//, '$1');
mydate = date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();

date.getMonth()返回0到11的整数,所以我们必须加1以获得正确的月份数

答案 34 :(得分:2)

我建议的最简单方法是在JS上使用正则表达式:

//Only use [0] if you are sure that the string matches the pattern
//Otherwise, verify if 'match' returns something
"/Date(1512488018202)/".match(/\d+/)[0] 

答案 35 :(得分:2)

尝试一下...

function formatJSONDate(jsonDate) {
            var date = jsonDate;
            var parsedDate = new Date(parseInt(date.toString().substring(6)));
            var newDate = new Date(parsedDate);
            var getMonth = newDate.getMonth() + 1;
            var getDay = newDate.getDay();
            var getYear = newDate.getFullYear(); 

            var standardDate = (getMonth<10 ? '0' : '') + getMonth + '/' + (getDay<10 ? '0' : '') + getDay + '/' + getYear;
            return standardDate;
        }

getYear()返回年份-1900,现在已经过时了,最好使用getFullYear()

答案 36 :(得分:1)

将JSON日期转换为JavaScript日期很容易:

var s = Response.StartDate;     
s = s.replace('/Date(', '');

s = s.replace(')/', '');

var expDate = new Date(parseInt(s));

答案 37 :(得分:0)

TLDR:您不能可靠地转换该仅日期的值,而是发送字符串...

...或者至少这就是几乎所有这些答案都应以这种方式开始的原因。

这里发生了许多转换问题。

这是没有时间的日期

每个人似乎都缺少的是问题中有多少尾随零-它几乎可以肯定是从没有时间的日期开始的。

/Date(1224043200000)/

从javascript控制台执行此操作作为新日期(许多答案的基础)

new Date(1224043200000)

您得到:

enter image description here

最初的询问者可能在EST中,并且具有纯日期(sql)或带有午夜的DateTime(不是DateTimeOffset)。

换句话说,这里的意图是时间部分没有意义。但是,如果浏览器在与生成它的服务器所在的时区相同的时区执行此命令,则无关紧要,并且大多数答案都起作用。

按时区排序

但是,如果您在具有不同时区(例如PST)的计算机上执行上述代码:

enter image description here

您会注意到,在这个其他时区,我们现在已经落后了。更改序列化器(仍将以iso格式包含时区)将无法解决此问题

问题

Date(sql)和DateTime(.net)上没有时区,但是一旦将它们转换为可以的时区(在这种情况下是通过json推断的javascript),. net中的默认操作就是当前时区。

序列化创建的数字是从unix纪元以来的毫秒数或:

(DateTimeOffset.Parse("10/15/2008 00:00:00Z") - DateTimeOffset.Parse("1/1/1970 00:00:00Z")).TotalMilliseconds;

这是javascript中new Date()所采用的参数。 Epoch来自UTC,因此无论您是否想要,现在都可以在那里获取时区信息。

可能的解决方案:

在您的序列化对象上创建仅代表日期的字符串属性可能更安全-带“ 10/15/2008”的字符串不太可能使其他人混淆。即使在那儿,您在解析方面也要小心: https://stackoverflow.com/a/31732581

但是,本着为所问问题提供答案的精神,

function adjustToLocalMidnight(serverMidnight){ 
  var serverOffset=-240; //injected from model? <-- DateTimeOffset.Now.Offset.TotalMinutes
  var localOffset=-(new Date()).getTimezoneOffset(); 
  return new Date(date.getTime() + (serverOffset-localOffset) * 60 * 1000)
}

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

答案 38 :(得分:0)

如果您使用Kotlin,则可以解决您的问题。

val dataString = "/Date(1586583441106)/"
val date = Date(Long.parseLong(dataString.substring(6, dataString.length - 2)))

答案 39 :(得分:-5)

你的JSON可能应该返回某种对象(好吧,它的字符串表示)。

"{ myDate : Date(1224043200000) }"

使用jQuery,您可以这样访问您的数据对象:

$.get(
    "myJSONFile.php",
    function (data) {
        // data.myDate will be a date object.

        // to show in a short date format (eg: dd/mm/yyyy)
        alert (
            data.myDate.getDate() + "/"
            + (data.myDate.getMonth() + 1) + "/"
            + data.myDate.getFullYear()
        ); // alerts: "15/10/2008"
    }
);