JS 时间戳与日期格式的相互转换

1. 将时间戳转换成日期格式:
function timestampToTime(timestamp) {
    let date = new Date(timestamp),
        Y = date.getFullYear() + '-',
        M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-',
        D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ',
        h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':',
        m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':',
        s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
        
    return Y + M + D + h + m + s;
}
timestampToTime(1403058804);

console.log(timestampToTime(1403058804)); // 2014-06-18 10:33:24

注意:如果是Unix时间戳记得乘以1000。比如:PHP函数time()获得的时间戳就要乘以1000

2. 将日期格式转换成时间戳:
let _date = new Date('2014-04-23 18:55:49:123');

// 有四种方式获取
let time1 = _date.getTime(); // 通过原型方法直接获得当前时间的毫秒值
let time2 = _date.valueOf(); // 返回指定对象的原始值获得准确的时间戳值
let time3 = Number(_date); // 将时间转化为一个number类型的数值,即时间戳
let time4 = Date.parse(_date); // 不推荐这种办法,毫秒级别的数值被转化为000

console.log(time1); // 1398250549123
console.log(time2); // 1398250549123
console.log(time3); // 1398250549123
console.log(time4); // 1398250549000

注意:获取到的时间戳除以1000就可获得Unix时间戳,就可传值给后台得到

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值