2013-10-08 110 views
3

這就是我在Ruby中所做的。Javascript - 將時間轉換爲整數並將整數轉換爲時間

time = Time.now 
=> 2013-10-08 12:32:50 +0530 
time.to_i //converts time to integer 
=> 1381215770 
Time.at(time.to_i) //converts integer to time 
=> 2013-10-08 12:32:50 +0530 

我想實現與Node.js一樣的,但不知道如何去做。請幫助我找到一個用Node.js,Javascript實現相同的模塊。謝謝!

回答

6

在javascript世界。

Date.now() 

and 

new Date(1381216317325); 
+2

需要注意的是,在JavaScript中,Date是從1970年1月1日00:00:00 UTC(Unix Epoch)(通常只有幾秒 - 在Ruby中)存儲的毫秒數,並且該Date.now()僅返回實際時間,如果您需要將任何Date對象轉換爲整數,請使用Date.getTime()。 – ivoszz

3

除了user10答案

Date.parse("2013-10-08 12:32:50 +0530"); 

將讓你時間整數

編輯
Date API

+0

我真的需要這個。謝謝! –

-1
new Date().getTime(); 

將返回一個整數代表自UTC 1970年1月1日午夜以來以毫秒爲單位的時間。這需要被解析爲更人性化的可讀性。

JavaScript中沒有默認的方法將這個數字轉化爲人類可解釋的日期,所以你必須自己寫。

一個簡單的方法是這樣的:

function getTime() { 
    var now = new Date(); 
    return ((now.getMonth() + 1) + '-' + 
      (now.getDate()) + '-' + 
      now.getFullYear() + " " + 
      now.getHours() + '-' + 
      ((now.getMinutes() < 10) 
       ? ("0" + now.getMinutes()) 
       : (now.getMinutes())) + ':' + 
      ((now.getSeconds() < 10) 
       ? ("0" + now.getSeconds()) 
       : (now.getSeconds()))); 
} 

console.log(getTime()); 

你可以調整自己出現的順序。