首頁  >  文章  >  web前端  >  javascript時間戳轉換成日期格式的用法實例詳解

javascript時間戳轉換成日期格式的用法實例詳解

伊谢尔伦
伊谢尔伦原創
2017-07-22 11:41:111560瀏覽

js需要把時間戳轉為普通格式,一般的情況下可能用不到的

#下面先來看第一種吧 

function getLocalTime(nS) { 
return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/,' '); 
} 
alert(getLocalTime(1293072805));

結果是
2010年12月23日10:53
第二種 

function getLocalTime(nS) { 
return new Date(parseInt(nS) * 1000).toLocaleString().substr(0,17)} 
alert(getLocalTime(1293072805));

如果你想得到這樣格式的怎麼辦呢?
2010-10-20 10:00:00
看下面程式碼吧 

function getLocalTime(nS) { 
return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " "); 
} 
alert(getLocalTime(1177824835));

也可以這樣寫的 

function formatDate(now) { 
var year=now.getYear(); 
var month=now.getMonth()+1; 
var date=now.getDate(); 
var hour=now.getHours(); 
var minute=now.getMinutes(); 
var second=now.getSeconds(); 
return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second; 
} 
var d=new Date(1230999938); 
alert(formatDate(d));

好了問題解決
要注意的是
不要把字串中的Date(這樣的字元也傳進去,要先處理一下,這樣很方便就能處理的
可以使用replace方法
如下: 

replace("/Date(","").replace(")/","");


以上是javascript時間戳轉換成日期格式的用法實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn