Javascript日期从毫秒和时区

时间:2012-11-28 21:31:07

标签: javascript jquery json datetime

  

可能重复:
  How to format a JSON date?
  Parsing Date from webservice

很抱歉,如果已经提出这个问题。我环顾四周但却找不到一个。是否有一种快速便捷的方式来转换" json "仅使用javascriptjQuery(不包括其他jQuery库)的日期为人类友好格式?

日期格式如下:

creationDate: "/Date(1346713200000+0100)/"

由于

1 个答案:

答案 0 :(得分:6)

> var maybeDateString = "/Date(1346713200000+0100)/";
> fromDateString(maybeDateString)
Tue Sep 04 2012 02:00:00 GMT+0200

function fromDateString(str) {
    var res = str.match(/\/Date\((\d+)(?:([+-])(\d\d)(\d\d))?\)\//);
    if (res == null)
        return new Date(NaN); // or something that indicates it was not a DateString
    var time = parseInt(res[1], 10);
    if (res[2] && res[3] && res[4]) {
        var dir = res[2] == "+" ? -1 : 1,
            h = parseInt(res[3], 10),
            m = parseInt(res[4], 10);
        time += dir * (h*60+m) * 60000;
    }
    return new Date(time);
}