从JavaScript中的日期中减去天

有谁知道约会(例如今天)和回溯X天的简单方法吗?

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

村村A小卤蛋2020/03/12 11:24:24

Try something like this

dateLimit = (curDate, limit) => {
    offset  = curDate.getDate() + limit
    return new Date( curDate.setDate( offset) )
}

currDate could be any date

limit could be the difference in number of day (positive for future and negative for past)

小宇宙神无2020/03/12 11:24:24

Using Modern JavaScript function syntax

const getDaysPastDate = (daysBefore, date = new Date) => new Date(date - (1000 * 60 * 60 * 24 * daysBefore));

console.log(getDaysPastDate(1)); // yesterday

さ恋旧る2020/03/12 11:24:24

If you want to both subtract a number of days and format your date in a human readable format, you should consider creating a custom DateHelper object that looks something like this :

var DateHelper = {
    addDays : function(aDate, numberOfDays) {
        aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays
        return aDate;                                  // Return the date
    },
    format : function format(date) {
        return [
           ("0" + date.getDate()).slice(-2),           // Get day and pad it with zeroes
           ("0" + (date.getMonth()+1)).slice(-2),      // Get month and pad it with zeroes
           date.getFullYear()                          // Get full year
        ].join('/');                                   // Glue the pieces together
    }
}

// With this helper, you can now just use one line of readable code to :
// ---------------------------------------------------------------------
// 1. Get the current date
// 2. Subtract 5 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), -5));

(see also this Fiddle)

神无Davaid2020/03/12 11:24:24

I get good mileage out of date.js:

http://www.datejs.com/

d = new Date();
d.add(-10).days();  // subtract 10 days

Nice!

Website includes this beauty:

Datejs doesn’t just parse strings, it slices them cleanly in two

宝儿猪猪西门2020/03/12 11:24:24

See the following code, subtract the days from the current date. Also, set the month according to substracted date.

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);
伽罗路易2020/03/12 11:24:24

When setting the date, the date converts to milliseconds, so you need to convert it back to a date:

This method also take into consideration, new year change etc.

function addDays( date, days ) {
    var dateInMs = date.setDate(date.getDate() - days);
    return new Date(dateInMs);
}

var date_from = new Date();
var date_to = addDays( new Date(), parseInt(days) );
乐逆天2020/03/12 11:24:24

for me all the combinations worked fine with below code snipplet , the snippet is for Angular-2 implementation , if you need to add days , pass positive numberofDays , if you need to substract pass negative numberofDays

function addSubstractDays(date: Date, numberofDays: number): Date {
let d = new Date(date);
return new Date(
    d.getFullYear(),
    d.getMonth(),
    (d.getDate() + numberofDays)
);
}
猴子蛋蛋2020/03/12 11:24:23

最佳答案导致我的代码出现错误,该错误将在本月的第一天设置当前月份的将来日期。这就是我所做的

curDate = new Date(); // Took current date as an example
prvDate = new Date(0); // Date set to epoch 0
prvDate.setUTCMilliseconds((curDate - (5 * 24 * 60 * 60 * 1000))); //Set epoch time
HarryLEY2020/03/12 11:24:23

I like the following because it is one line. Not perfect with DST changes but usually good enough for my needs.

var fiveDaysAgo = new Date(new Date() - (1000*60*60*24*5));
路易Stafan2020/03/12 11:24:23

我创建了一个用于日期操作的函数。您可以添加或减去任何天数,小时数,分钟数。

function dateManipulation(date, days, hrs, mins, operator) {
   date = new Date(date);
   if (operator == "-") {
      var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
      var newDate = new Date(date.getTime() - durationInMs);
   } else {
      var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
      var newDate = new Date(date.getTime() + durationInMs);
   }
   return newDate;
 }

现在,通过传递参数来调用此函数。例如,这是一个函数调用,用于获取从今天起3天之前的日期。

var today = new Date();
var newDate = dateManipulation(today, 3, 0, 0, "-");
Sam伽罗2020/03/12 11:24:23

function addDays (date, daysToAdd) {
  var _24HoursInMilliseconds = 86400000;
  return new Date(date.getTime() + daysToAdd * _24HoursInMilliseconds);
};

var now = new Date();

var yesterday = addDays(now, - 1);

var tomorrow = addDays(now, 1);

蛋蛋古一2020/03/12 11:24:23

无需使用第二个变量,您可以将x替换为x天:

let d=new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000))
Stafan逆天2020/03/12 11:24:23

我发现getDate()/ setDate()方法存在一个问题,即它太容易将所有内容转换为毫秒,并且有时语法难以理解。

相反,我想解决一个事实,即1天= 86,400,000毫秒。

因此,对于您的特定问题:

today = new Date()
days = 86400000 //number of milliseconds in a day
fiveDaysAgo = new Date(today - (5*days))

奇迹般有效。

我一直在使用这种方法进行30/60/365天的滚动计算。

您可以轻松地对此进行推断,以创建几个月,几年等的时间单位。

逆天西里2020/03/12 11:24:23

一些现有的解决方案已经接近,但与我想要的不完全相同。此函数可使用正值或负值,并处理边界情况。

function addDays(date, days) {
    return new Date(
        date.getFullYear(),
        date.getMonth(),
        date.getDate() + days,
        date.getHours(),
        date.getMinutes(),
        date.getSeconds(),
        date.getMilliseconds()
    );
}
番长西里神无2020/03/12 11:24:23

我喜欢以毫秒为单位进行数学运算。所以用Date.now()

var newDate = Date.now() + -5*24*3600*1000; // date 5 days ago in milliseconds

如果您喜欢它的格式

new Date(newDate).toString(); // or .toUTCString or .toISOString ...

注意:Date.now()在较旧的浏览器(例如我认为的IE8)中不起作用。Polyfill在这里

2015年6月更新

@socketpair指出了我的草率。正如他/她所说:“由于时区规则,一年中的某天有23个小时,有25个小时”。

进一步来说,如果您想计算夏令时更改的时区中的5天前的本地日,并且上面的答案存在夏令时错误,并且您

  • 假设(错误地)Date.now()为您提供了当前的本地时间,或者
  • 用途.toString(),它返回本地日期,因此与Date.now()UTC中基准日期不兼容

但是,如果您全部使用UTC进行数学运算,则可以使用它,例如

答:您希望UTC日期从NOW(UTC)5天前开始

var newDate = Date.now() + -5*24*3600*1000; // date 5 days ago in milliseconds UTC
new Date(newDate).toUTCString(); // or .toISOString(), BUT NOT toString

B.您使用UTC基准日期(不是“现在”)开始,使用 Date.UTC()

newDate = new Date(Date.UTC(2015, 3, 1)).getTime() + -5*24*3600000;
new Date(newDate).toUTCString(); // or .toISOString BUT NOT toString
逆天AGreen2020/03/12 11:24:23

我注意到getDays + X在日期/月份范围内不起作用。只要您的日期不早于1970,就可以使用getTime。

var todayDate = new Date(), weekDate = new Date();
weekDate.setTime(todayDate.getTime()-(7*24*3600000));
Jim古一2020/03/12 11:24:23

我为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);
小卤蛋Tom2020/03/12 11:24:23

它是这样的:

var d = new Date(); // today!
var x = 5; // go back 5 days!
d.setDate(d.getDate() - x);
十三飞云斯丁2020/03/12 11:24:23
var dateOffset = (24*60*60*1000) * 5; //5 days
var myDate = new Date();
myDate.setTime(myDate.getTime() - dateOffset);

如果您要在整个Web应用程序中执行很多头痛检查日期操作,DateJS将使您的生活更加轻松:

http://simonwillison.net/2007/Dec/3/datejs/