js 時間戳與日期時間的轉換

// 獲取當前時間戳(以s爲單位)
var timestamp = Date.parse(new Date());
timestamp = timestamp / 1000;
//當前時間戳爲:1403149534
console.log("當前時間戳爲:" + timestamp);

// 獲取某個時間格式的時間戳
var stringTime = "2014-07-10 10:21:12";
var timestamp2 = Date.parse(new Date(stringTime));
timestamp2 = timestamp2 / 1000;
//2014-07-10 10:21:12的時間戳爲:1404958872 
console.log(stringTime + "的時間戳爲:" + timestamp2);

// 將當前時間換成時間格式字符串
var timestamp3 = 1403058804;
var newDate = new Date();
newDate.setTime(timestamp3 * 1000);
// Wed Jun 18 2014 
console.log(newDate.toDateString());
// Wed, 18 Jun 2014 02:33:24 GMT 
console.log(newDate.toGMTString());
// 2014-06-18T02:33:24.000Z
console.log(newDate.toISOString());
// 2014-06-18T02:33:24.000Z 
console.log(newDate.toJSON());
// 2014年6月18日 
console.log(newDate.toLocaleDateString());
// 2014年6月18日 上午10:33:24 
console.log(newDate.toLocaleString());
// 上午10:33:24 
console.log(newDate.toLocaleTimeString());
// Wed Jun 18 2014 10:33:24 GMT+0800 (中國標準時間)
console.log(newDate.toString());
// 10:33:24 GMT+0800 (中國標準時間) 
console.log(newDate.toTimeString());
// Wed, 18 Jun 2014 02:33:24 GMT
console.log(newDate.toUTCString());
var str = '2013-08-30'; // 日期字符串

str = str.replace(/-/g,'/'); // 將-替換成/,由於下面這個構造函數只支持/分隔的日期字符串

var date = new Date(str); // 構造一個日期型數據,值爲傳入的字符串

 



在上面,new Date(str)構造了一個日期,參數str至少要提供年月日三部分,也就是形如「2013/03/08」的字符串,不能是"2013/03",不然將獲得一個NaN。此時構造出來的時間是:2013/03/08 00:00:00。同時你還能夠傳入小時、分鐘和秒數,但不能只傳入小時,好比「2013/03/08 17」,這樣的參數一樣會獲得一個NaN。參數能夠是「2013/03/08 17:20」或者「2013/03/08 17:20:05」,這樣均可以獲得正確的時間,其中若是秒數沒給出,則默認爲0。

此時獲得的是日期型數據,若是要獲得上面所謂的時間戳,能夠這樣:
var time = date.getTime();
相關文章
相關標籤/搜索