将时间戳转换为日期格式

前端在调接口的时候,后台返回来的时间是一串时间戳,这里就提供一个时间戳转化为时间格式的方法

// 参数 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];   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值