关于时间的方法

1.获取前后几天的时间(年月日)

function getNowFormatDate(num) {
    var today = new Date();
    var time=today.getTime() + 1000*60*60*24*num;
    var date=new Date(time);
    var seperator1 = "-";
    var month = date.getMonth() + 1;
    var strDate = date.getDate()+num;
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
    return currentdate;
}

2.获取当前时间(年月日时分秒)

function dateFormat(date){
      console.log(date)
      const daterc = date
      if(daterc!=null){
        const dateMat= new Date(daterc);
        const year = dateMat.getFullYear();
        const month = dateMat.getMonth() + 1;
        const day = dateMat.getDate();
        const hh = dateMat.getHours();
        const mm = dateMat.getMinutes();
        const ss = dateMat.getSeconds();
        return year + "-" + (month < 10 ? "0" : "") + month + "-" + (day < 10 ? "0" : "") + day+" "+ (hh < 10 ? "0" : "") + hh + ":" + (mm < 10 ? "0" : "") + mm+ ":" + (ss < 10 ? "0" : "") + ss;
      }
    }
function getNowFormatDate() {
    var date = new Date();
    // var seperator1 = "-";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    var hours = date.getHours(); // 获取当前小时数(0-23)
    var minutes = date.getMinutes(); // 获取当前分钟数(0-59)
    var seconds = date.getSeconds(); // 获取当前秒数(0-59)
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if (hours >= 0 && hours <= 9) {
        hours = "0" + hours;
    }
    if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
    }
    if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
    }
    var currentdate = date.getFullYear() + "-" + month + "-" + strDate + " " + hours + ":" + minutes + ":" + seconds;
    return currentdate;
}

3.获取今天星期几

var str = '今天是星期' + '日一二三四五六'.charAt(new Date().getDay())
    console.log(str)

你可能感兴趣的:(关于时间的方法)