2012-10-12 151 views
20

我想使用jQuery的TIMEAGO插件 - http://timeago.yarp.com/轉換Unix時間戳到ISO 8601

我有這樣1331209044000時間戳和文檔說我需要一個ISO 8601時間戳。

說實話,我從來沒有聽說過ISO 8601

的我如何轉換呢?

乾杯

+0

有關標準的更多信息,請參閱http://en.wikipedia.org/wiki/ISO_8601。恐怕你只需要根據'Date'組件構建一個字符串。 – Jacob

+2

這看起來很有希望:http://stackoverflow.com/questions/2573521/how-do-i-output-an-iso-8601-formatted-string-in-javascript – Aeoril

回答

41

假設你的時間戳是以毫秒爲單位(或可以轉換成毫秒容易),那麼你可以使用Date constructordate.toISOString() method

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

如果目標不支持EMCAScript第5版,那麼你可以使用這個問題列出的策略舊的瀏覽器:How do I output an ISO 8601 formatted string in JavaScript?

+0

這是ECMAScript 5 - 請參閱這裏的兼容性和後備代碼:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toISOString – Aeoril

+1

不要忘記,該unix時間戳記是在幾秒鐘內,但Javascript計數以毫秒爲單位。所以它實際上是'new Date(timestamp * 1000).toISOString();'。 –

0

我使用的解決方案,這要歸功於提供

// 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

當然,這個函數假定日期實際上是在祖魯語(GMT + 0)時區。 – maerics