时间戳转日期和日期转时间及时间戳倒计时

//获取当前时间,格式YYYY-MM-DD
//方法一
function nowtime() {
    var date = new Date()
    var seperator1 = '-'
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var strDate = date.getDate()
    if (month >= 1 && month <= 9) {
        month = '0' + month
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate
    return currentdate
}
//方法二
var dqrq = new Date();
var nowtime = time(dqrq.getFullYear()) + '-' + time((dqrq.getMonth() + 1)) + '-' + time(dqrq.getDate());
function time(s) {
    return s < 10 ? '0' + s : s;
}

时间戳和日期互相转换在开发时经常用到,简单整理如下:

//时间戳转日期
function timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    var D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
    var h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0'+(date.getSeconds()) : date.getSeconds());
    return Y+M+D+h+m+s;
}
timestampToTime(1403058804);
日期转时间戳
function DateToUnix(string) {
    var f = string.split(' ', 2);
    var d = (f[0] ? f[0] : '').split('-', 3);
    var t = (f[1] ? f[1] : '').split(':', 3);
    return (new Date(
        parseInt(d[0], 10) || null, (parseInt(d[1], 10) || 1) - 1, parseInt(d[2], 10) || null, parseInt(t[0], 10) || null, parseInt(t[1], 10) || null, parseInt(t[2], 10) || null)).getTime() / 1000;
};

时间戳倒计时

var oTime="1607592644000"; //毫秒
var oPerTime=(new Date()).getTime();
function countdown(){
    var oPerTime=(new Date()).getTime();
    var oT=oTime-oPerTime;
    d = Math.floor(oT/1000/60/60/24);
    h = Math.floor(oT/1000/60/60%24);
    m = Math.floor(oT/1000/60%60);
    s = Math.floor(oT/1000%60);
    $('.countdown').html("<span>"+touDou(d)+"</span>天<span>"+touDou(h)+"</span>时<span>"+touDou(m)+"</span>分<span>"+touDou(s)+"</span>秒")
}
countdown();
// 补零
function touDou(n){
    return n>9? n:"0"+n;
}
setInterval(countdown,1000);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值