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");

原文地址:https://www.cnblogs.com/coder-lzh/p/9012860.html