前端在调接口的时候,后台返回来的时间是一串时间戳,这里就提供一个时间戳转化为时间格式的方法
// 参数 str 为时间戳 可以传入10位也可以传入13位
// 参数 bool的值可传true或者false或者不传,如果需要显示秒则传true,不需要显示则传false或者不传
function getMyDate(str, bool){
if(str > 9999999999) { // 这里判断:时间戳为几位数
var c_Date = new Date(parseInt(str));
} else {
var c_Date = new Date(parseInt(str) * 1000);
}
var c_Year = c_Date.getFullYear(),
c_Month = c_Date.getMonth()+1,
c_Day = c_Date.getDate(),
c_Hour = c_Date.getHours(),
c_Min = c_Date.getMinutes(),
c_Sen = c_Date.getSeconds();
if(bool) { // 判断是否需要显示秒
var c_Time = c_Year +'-'+ getzf(c_Month) +'-'+ getzf(c_Day) +' '+ getzf(c_Hour) +':'+ getzf(c_Min) +':'+getzf(c_Sen);//最后拼接时间
} else {
var c_Time = c_Year +'-'+ getzf(c_Month) +'-'+ getzf(c_Day) +' '+ getzf(c_Hour) +':'+ getzf(c_Min);//最后拼接时间
}
return c_Time;
};
//补0操作 小于10的就在数字前面加0,这应该很好理解吧
function getzf(c_num){
if(parseInt(c_num) < 10){
c_num = '0' + c_num;
}
return c_num;
}
// 用法:
// 需要显示秒:getMyDate(1523927510, true)
// 不需要显示秒: getMyDate(1523927510, false) ② getMyDate(1523927510)
// 如果只需要时间: getMyDate(1523927510, true).split(" ")[1];
// 如果只需要日期: getMyDate(1523927510, true).split(" ")[0];