js常用時間方法

學前端的小新發表於2018-11-23

1.時間轉年月日格式

function toLocaleDateString(timestamp){
    var toChangeDate = new Date(timestamp);
    var year = toChangeDate.getFullYear();
    var month = toChangeDate.getMonth();
    var day = toChangeDate.getDay();
    return year + "年" + month + "月" + day +"日";
}複製程式碼

2.時間轉成年月日時分秒格式

function toLocaleString(timestamp){
       var toChangeDate = new Date(timestamp);
       var year = toChangeDate.getFullYear();
       var month = toChangeDate.getMonth();
       var day = toChangeDate.getDay();
       var hour = toChangeDate.getHours();
       var min = toChangeDate.getMinutes();
       var sec = toChangeDate.getSeconds();
       return year + "年" + month + "月" + day +"日"+" "+hour+"時"+min+"分"+sec+"秒" ;
}複製程式碼

3.給定日期與當前時間比較

function dateDiffCurrent(time){
    var time1 = new Date(time).getTime();
    var time2 = new Date().getTime();
    if(time1>time2){
        return false
   }
   return true;
}複製程式碼

4.倒數計時

function countDown(time){
    var time = time;
    var end = new Date(time).getTime();
    var now = new Date().getTime();
       var lefttime = end-now;
    if(now>=end){
        alert("時間到");
        return;
   }else{
        var add0=function(val){
            return val<10?"0"+val:val
      }
        var h,m,s;
        h = Math.floor(lefttime/60/60/1000);
        m = Math.floor(lefttime/60/1000%60);
        s = Math.floor(lefttime/1000%60);
        console.log(h+":"+add0(m)+":"+add0(s));
   }
   setTimeout(function(){
           date.countDown(time)
   },1000)
}複製程式碼


相關文章