当当前日期是一月时,如何从当前日期获取一个月前的日期?

How to get the date one month before from current date, when current date is January?

我使用了一个名为 jQRnageSlider 的插件并试图获取滑块中显示的日期和时间标签,但是当我将滑块回滚到去年时,12 月份变成了 [=12] =] 最终。

正常情况,如果我不回滚到去年。

立即跳转到 2016 年 11 月

那应该是日期格式问题。有人可以帮忙吗?

$(".date-range-slider").dateRangeSlider({    
  ...

  formatter: function(val){
    var days = ('0' + val.getDate()).slice(-2),
    month = ('0' + val.getMonth() + 1).slice(-2),
    year = val.getFullYear(),
    hour = ('0' + val.getHours()).slice(-2),
    min = ('0' + val.getMinutes()).slice(-2);
    return days + "-" + month + "-" + year + " " + hour + ":" + min;
  }
});

问题在于那一行:

month = ('0' + val.getMonth() + 1).slice(-2)

你想从数学上求和而不是字符串,所以你应该这样做:

month = ('0' + (val.getMonth() + 1)).slice(-2)

检查代码片段以查看您的代码实际返回的内容:

var val = new Date();
document.write('0' + val.getMonth() + 1)

什么 returns 更正版本:

var val = new Date();
document.write('0' + (val.getMonth() + 1))