-1

I have the following timestamp (example) 20131024010907

that I would like to convert to date format. I will be subtracting the time stamp from another timestamp. For example:

20131024010907 - 20131024010856 = 11 seconds have elapsed

The problem is that if I subtract the timestamps as is, it will not work properly. E.g.

var x = 20131024010907
var y = 20131024010856
x-y != 11
x-y = 51

How would I convert these timestamps to dates in javascript so I can subtract them from each other? Is this possible?

4

2 回答 2

4

这些在我看来不像通常意义上的“时间戳”值(自大纪元 [1970 年 1 月 1 日格林威治标准时间午夜] 以来的秒数或毫秒数),它们看起来像打包的日期/时间字符串:

20131024010907
yyyyMMddHHmmss

如果是这样,您只需拆分字符串并使用new Date(year, month, day, hour, minute, second)构造函数:

var x = parseDate("20131024010907");
var y = parseDate("20131024010856");

console.log("x - y = " + (x - y) + "ms"); // 11000ms = 11 seconds

function parseDate(str) {
    return new Date(
        parseInt(str.substring(0, 4), 10),
        parseInt(str.substring(4, 6), 10) - 1, // Months start with 0
        parseInt(str.substring(6, 8), 10),
        parseInt(str.substring(8, 10), 10),
        parseInt(str.substring(10, 12), 10),
        parseInt(str.substring(12), 10)
    );
}

实例| 资源

于 2013-10-28T06:39:21.303 回答
1

您应该将时间戳转换为几乎 ISO 日期,然后使用 Date 构造函数:(小提琴:http: //jsfiddle.net/6d6hU/

var ts = "20131024010907";

var isoTs = ts.substring(0,4) + "-" + ts.substring(4,6) + "-" + ts.substring(6,8) + " " + ts.substring(8,10) + ":" + ts.substring(10, 12) + ":" + ts.substring(12)

console.log(isoTs)
console.log(new Date(isoTs))

还有更容易的事情。使用 moment.js 解析日期,格式与您的时间戳匹配:http: //momentjs.com/docs/#/parsing/string-format/

于 2013-10-28T06:41:20.637 回答