有没有一种简单的方法来获取olain JavaScript日期(例如今天)并返回X天?

例如,如果我想计算今天前5天的日期。


当前回答

var my date = new Date().toISOString().substring(0, 10);

它只能给你2014-06-20这样的日期。希望会有所帮助

其他回答

var my date = new Date().toISOString().substring(0, 10);

它只能给你2014-06-20这样的日期。希望会有所帮助

我为Date制作了这个原型,这样我就可以传递负值来减去天数,传递正值来添加天数。

if(!Date.prototype.adjustDate){
    Date.prototype.adjustDate = function(days){
        var date;

        days = days || 0;

        if(days === 0){
            date = new Date( this.getTime() );
        } else if(days > 0) {
            date = new Date( this.getTime() );

            date.setDate(date.getDate() + days);
        } else {
            date = new Date(
                this.getFullYear(),
                this.getMonth(),
                this.getDate() - Math.abs(days),
                this.getHours(),
                this.getMinutes(),
                this.getSeconds(),
                this.getMilliseconds()
            );
        }

        this.setTime(date.getTime());

        return this;
    };
}

因此,为了使用它,我可以简单地写下:

var date_subtract = new Date().adjustDate(-4),
    date_add = new Date().adjustDate(4);
function daysSinceGivenDate (date) {
  const dateInSeconds = Math.floor((new Date().valueOf() - date.valueOf()) / 1000);
  const oneDayInSeconds = 86400;

  return Math.floor(dateInSeconds / oneDayInSeconds); // casted to int
};

console.log(daysSinceGivenDate(new Date())); // 0
console.log(daysSinceGivenDate(new Date("January 1, 2022 03:24:00"))); // relative...

请参见以下代码,从当前日期减去天数。此外,根据减去的日期设置月份。

var today = new Date();
var substract_no_of_days = 25;

today.setTime(today.getTime() - substract_no_of_days* 24 * 60 * 60 * 1000);
var substracted_date = (today.getMonth()+1) + "/" +today.getDate() + "/" + today.getFullYear();

alert(substracted_date);

尝试以下操作:

 var d = new Date();
 d.setDate(d.getDate()-5);

注意,这将修改日期对象并返回更新日期的时间值。

var d=新日期();document.write('今天是:'+d.toLocaleString());d.setDate(d.getDate()-5);document.write('<br>5天前是:'+d.toLocaleString());