json轉換時間格式爲一般格式
網上有好多說json傳過來的時間格式是 /Date(1436595149269)/ 這種類型
其中較爲簡單實用的方法如下:
<script>
//yyyy-MM-dd HH:mm:SS
function getDateTime(date) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hh = date.getHours();
var mm = date.getMinutes();
var ss = date.getSeconds();
return year + "-" + month + "-" + day + " " + hh + ":" + mm + ":" + ss;
}
//調用的是這個方法
function ConvertJSONDateToJSDate(jsondate) {
var date = new Date(parseInt(jsondate.replace("/Date(", "").replace(")/", ""), 10));
return date;
}
var date = "/Date(1379944571737)/";
alert(getDateTime(ConvertJSONDateToJSDate(date)));
</script>
- 而我遇到的問題是:
Object { szphid: 36, szphtitle: "213", szphauthor: "123321", szphdate: 1508969100000, szphdw: "中建路橋集團有限公司", szphaddress: "就業報告廳", szphcontent: "<p>1233213</p> " }
其中時間爲szphdate: 1508969100000,這應該是後臺傳回的毫秒數,我想讓它變成HH:mm格式
但是date.getHours()和date.getMinutes()的返回值如果<10,將會返回一位的小時數和分數,所以我加了一個簡單的方法實現無論何時,返回值都是兩位:
function getDateTime(date) {
var hh = date.getHours();
hh = checkTime(hh)
var mm = date.getMinutes();
//var ss = date.getSeconds();
mm = checkTime(mm)
console.log(hh+":"+mm)
return hh + ":" + mm ;
}
/* date.getHours();
* date.getMinutes();
*當hh 和 mm < 10時也顯示兩位數字
*
* */
function checkTime(i)
{
if (i<10)
{i="0" + i}
return i
}
調用方法爲:
var date =1508969100000;
date=new Date(parseInt(date))
date = getDateTime(date)
//console.log(date)
結果是:
06:05