js格式化日期工具類


就是一個工具類  開箱即用

傳進一個指定的參數,格式化

//將時間戳格式化 
function getMyDate(time){  
    if(typeof(time)=="undefined"){
        return "";
    }
    var oDate = new Date(time),  
     oYear = oDate.getFullYear(),  
     oMonth = oDate.getMonth()+1,  
     oDay = oDate.getDate(),  
     oHour = oDate.getHours(),  
     oMin = oDate.getMinutes(),  
     oSen = oDate.getSeconds(),  
     oTime = oYear +'-'+ getzf(oMonth) +'-'+ getzf(oDay) +' '+ getzf(oHour) +':'+ getzf(oMin) +':'+getzf(oSen);//最后拼接時間  
            
     return oTime;  
    };
    
     //補0操作,當時間數據小於10的時候,給該數據前面加一個0  
    function getzf(num){  
        if(parseInt(num) < 10){  
            num = '0'+num;  
        }  
        return num;  
    }

 獲取當前的日期時間 格式“yyyy-MM-dd HH:MM:SS”

function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    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 = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + date.getHours() + seperator2 + date.getMinutes()
            + seperator2 + date.getSeconds();
    return currentdate;
}

獲取當前時間,格式YYYY-MM-DD

 function getNowFormatDate() {
        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;
    }

 

獲取當前的星期幾

//一行啊~~!TMD居然一樣代碼就寫了
var str = "今天是星期" + "日一二三四五六".charAt(new Date().getDay());
console.log(str);

 

給出一個日期,計算與當前時間還有多少天 

//計算日期相減天數
    function DateMinus(time){
      var sdate = new Date(time);
      var now = new Date();
      var days = now.getTime() - sdate.getTime();
      var day = parseInt(days / (1000 * 60 * 60 * 24));
      return day;
    }
    let number = DateMinus();
    console.log(number)

time 只要是符合時間格式的字符串就行。比如:
var sdate = new Date("Sep 22, 2018 12:00:00 AM");
var sdate = new Date("2018-8-09");
 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM