JS時間戳和時間之間轉換


一、時間轉換時間戳

var date = new Date(); //時間對象
var str = date.getTime(); //轉換成時間戳

 

 

 

二、時間戳轉換為時間

 

1.轉換成形如  格式:

function getDate(date){ 
    var t = new Date(date).toLocaleString(); 
    return t; 
}

 

 

2.還可以這樣

 

// 也很簡單
var strtime = '2014-04-23 18:55:49:123';

var date = new Date(strtime.replace(/-/g, '/'));

// 有三種方式獲取,在后面會講到三種方式的區別
time1 = date.getTime();
time2 = date.valueOf();
time3 = Date.parse(date);

/* 
三種獲取的區別:
第一、第二種:會精確到毫秒
第三種:只能精確到秒,毫秒將用0來代替
比如上面代碼輸出的結果(一眼就能看出區別):
1398250549123
1398250549123
1398250549000 
*/
 

 

 

3. 轉換成更多其他的格式:

// 簡單的一句代碼
var date = new Date(時間戳); //獲取一個時間對象

/**
 1. 下面是獲取時間日期的方法,需要什么樣的格式自己拼接起來就好了
 2. 更多好用的方法可以在這查到 -> http://www.w3school.com.cn/jsref/jsref_obj_date.asp
 */
date.getFullYear();  // 獲取完整的年份(4位,1970)
date.getMonth();  // 獲取月份(0-11,0代表1月,用的時候記得加上1)
date.getDate();  // 獲取日(1-31)
date.getTime();  // 獲取時間(從1970.1.1開始的毫秒數)
date.getHours();  // 獲取小時數(0-23)
date.getMinutes();  // 獲取分鍾數(0-59)
date.getSeconds();  // 獲取秒數(0-59)

 

 
        

例子

// 比如需要這樣的格式 yyyy-MM-dd hh:mm:ss
var date = new Date(1398250549490);
Y = date.getFullYear() + '-';
M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
D = date.getDate() + ' ';
h = date.getHours() + ':';
m = date.getMinutes() + ':';
s = date.getSeconds(); 
console.log(Y+M+D+h+m+s); 
// 輸出結果:2014-04-23 18:55:49

 

 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM