// 獲取當前時間戳(以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();