将Unix时间戳转换为ISO 8601

时间:2021-09-09 21:30:43

I want to use the jquery timeago plugin - http://timeago.yarp.com/

我想使用jquery timeago插件 - http://timeago.yarp.com/

I have timestamps like this 1331209044000 and the docs say i need an ISO 8601 timestamp.

我有这样的时间戳1331209044000,文档说我需要ISO 8601时间戳。

To be honest i have never heard of ISO 8601.

说实话,我从未听说过ISO 8601。

How can i convert it?

我怎么能转换它?

Cheers

干杯

2 个解决方案

#1


43  

Assuming your timestamp is in milliseconds (or you can convert to milliseconds easily) then you can use the Date constructor and the date.toISOString() method.

假设您的时间戳以毫秒为单位(或者您可以轻松转换为毫秒),那么您可以使用Date构造函数和date.toISOString()方法。

var s = new Date(1331209044000).toISOString();
s; // => "2012-03-08T12:17:24.000Z"

If you target older browsers which do not support EMCAScript 5th Edition then you can use the strategies listed in this question: How do I output an ISO 8601 formatted string in JavaScript?

如果您的目标是不支持EMCAScript 5th Edition的旧浏览器,那么您可以使用此问题中列出的策略:如何在JavaScript中输出ISO 8601格式的字符串?

#2


0  

The solution i used, thanks to the links provided

由于提供的链接,我使用的解决方案

// convert to ISO 8601 timestamp
function ISODateString(d){
    function pad(n){return n<10 ? '0'+n : n}
    return d.getUTCFullYear()+'-'
        + pad(d.getUTCMonth()+1)+'-'
        + pad(d.getUTCDate())+'T'
        + pad(d.getUTCHours())+':'
        + pad(d.getUTCMinutes())+':'
        + pad(d.getUTCSeconds())+'Z'
}

var d = new Date(parseInt(date));
console.log(ISODateString(d));

#1


43  

Assuming your timestamp is in milliseconds (or you can convert to milliseconds easily) then you can use the Date constructor and the date.toISOString() method.

假设您的时间戳以毫秒为单位(或者您可以轻松转换为毫秒),那么您可以使用Date构造函数和date.toISOString()方法。

var s = new Date(1331209044000).toISOString();
s; // => "2012-03-08T12:17:24.000Z"

If you target older browsers which do not support EMCAScript 5th Edition then you can use the strategies listed in this question: How do I output an ISO 8601 formatted string in JavaScript?

如果您的目标是不支持EMCAScript 5th Edition的旧浏览器,那么您可以使用此问题中列出的策略:如何在JavaScript中输出ISO 8601格式的字符串?

#2


0  

The solution i used, thanks to the links provided

由于提供的链接,我使用的解决方案

// convert to ISO 8601 timestamp
function ISODateString(d){
    function pad(n){return n<10 ? '0'+n : n}
    return d.getUTCFullYear()+'-'
        + pad(d.getUTCMonth()+1)+'-'
        + pad(d.getUTCDate())+'T'
        + pad(d.getUTCHours())+':'
        + pad(d.getUTCMinutes())+':'
        + pad(d.getUTCSeconds())+'Z'
}

var d = new Date(parseInt(date));
console.log(ISODateString(d));