JS日期相减得到天数

根据当天获取某一天(分享点自己收藏的干货)

function GetDay(day){

    function doHandleMonth(month){

      var m = month;

      if(month.toString().length == 1){

        m = "0" + month;

      }

      return m;

    };

    var today = new Date();

    var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;

    today.setTime(targetday_milliseconds); //注意,这行是关键代码

    var tYear = today.getFullYear();

    var tMonth = today.getMonth();

    var tDate = today.getDate();

    tMonth = doHandleMonth(tMonth + 1);

    tDate = doHandleMonth(tDate);

    return tYear+"-"+tMonth+"-"+tDate;

};

console.log(getDay(0))//当天

console.log(getDay(-7))//7天前

console.log(getDay(7))//7天后


你可能感兴趣的:(JS日期相减得到天数)