在我们开发的过程中,经验会用到ajax请求php发来的数据,而时间戳又往往是一个经常会遇到的东西,这一块处理起来,有些朋友还不太会,那么现在我把具体方法写一下,希望能帮助到大家。
首先,在script里面,定义一个方法,具体如下:
function formatDate(now) {
var year = now.getFullYear(),
month = now.getMonth() + 1,
date = now.getDate(),
hour = now.getHours(),
minute = now.getMinutes(),
second = now.getSeconds();
return year + "-" + month + "-" + date;
}
然后再处理接收过来的时间戳数据
var time = formatDate(new Date(data['time']*1000));
【注意事项】
1、在调用formatDate方法时,切记里面要有new Date。
2、另外,得到的时间,必须乘以1000。(具体为啥我也不知道,网上有不少说出现NaN-NaN-NaN的解决方法,感觉都不如这个好使。