从 JavaScript 中的日期中减去天、月、年

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37002681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:48:43  来源:igfitidea点击:

Subtract days, months, years from a date in JavaScript

javascript

提问by user3378165

Does anybody know of a simple way of taking a date (e.g. Today) and going back X days, X months and X years?

有人知道约会(例如今天)并返回 X 天、X 个月和 X 年的简单方法吗?

I have tried that:

我试过了:

var date = new Date();
$("#searchDateFrom").val((date.getMonth() -1 ) + '/' + (date.getDate() - 6) + '/' + (date.getFullYear() - 1));

But I got a negative date, for example today the output was:

但是我得到了一个否定的日期,例如今天的输出是:

3/-3/2015

3/-3/2015

Any advise?

有什么建议吗?

Thanks.

谢谢。

回答by gurvinder372

You are simply reducing the values from a number. So substracting 6 from 3 (date) will return -3 only.

您只是从数字中减少值。因此,从 3(日期)中减去 6 只会返回 -3。

You need to individually add/remove unit of time in date object

您需要在日期对象中单独添加/删除时间单位

var date = new Date();
date.setDate( date.getDate() - 6 );
date.setFullYear( date.getFullYear() - 1 );
$("#searchDateFrom").val((date.getMonth() ) + '/' + (date.getDate()) + '/' + (date.getFullYear()));

回答by Phil

As others have said you're subtracting from the numeric values returned from methods like date.getDate(), you need to reset those values on your date variable. I've created a method below that will do this for you. It creates a date using new Date()which will initialize with the current date, then sets the date, month, and year according to the values passed in. For example, if you want to go back 6 days then pass in -6 like so var newdate = createDate(-6,0,0). If you don't want to set a value pass in a zero (or you could set default values). The method will return the new date for you (tested in Chrome and Firefox).

正如其他人所说,您正在从从 等方法返回的数值中减去date.getDate(),您需要在日期变量上重置这些值。我在下面创建了一个方法来为你做这件事。它创建一个日期 using new Date(),该日期将使用当前日期进行初始化,然后根据传入的值设置日期、月份和年份。例如,如果您想返回 6 天,则像这样传入 -6 var newdate = createDate(-6,0,0)。如果您不想设置零值传递(或者您可以设置默认值)。该方法将为您返回新日期(在 Chrome 和 Firefox 中测试)。

function createDate(days, months, years) {
        var date = new Date(); 
        date.setDate(date.getDate() + days);
        date.setMonth(date.getMonth() + months);
        date.setFullYear(date.getFullYear() + years);
        return date;    
    }

回答by FvB

I'd recommend using the MomentJS libraries. They make all interactions with Dates a lot simpler.

我建议使用 MomentJS 库。它们使与日期的所有交互变得更加简单。

If you use Moment, your code would be as simple as this:

如果您使用 Moment,您的代码将像这样简单:

var today = moment();
var nextMonth = today.add('month', 1);
// note that both variables `today` and `nextMonth` refer to 
// the next month at this point, because `add` mutates in-place

You can find MomentJS here: http://momentjs.com/

你可以在这里找到 MomentJS:http://momentjs.com/

UPDATE:

更新:

In JavaScript, the Date.getDate() function returns the current day of the month from 1-31. You are subtracting 6 from this number, and it is currently the 3rd of the month. This brings the value to -3.

在 JavaScript 中,Date.getDate() 函数从 1 到 31 返回该月的当前日期。你正在从这个数字中减去 6,现在是这个月的 3 号。这使值变为 -3。

回答by N8allan

This is a pure-function which takes a passed-in starting date, building on Phil's answer:

这是一个纯函数,它采用传入的开始日期,以 Phil 的回答为基础:

function deltaDate(input, days, months, years) {
    return new Date(
      input.getFullYear() + years, 
      input.getMonth() + months, 
      Math.min(
        input.getDate() + days,
        new Date(input.getFullYear() + years, input.getMonth() + months + 1, 0).getDate()
      )
    );
}

e.g. writes the date one month ago to the console log:

例如将一个月前的日期写入控制台日志:

console.log(deltaDate(new Date(), 0, -1, 0));

e.g. subtracts a month from March 30, 2020:

例如,从 2020 年 3 月 30 日减去一个月:

console.log(deltaDate(new Date(2020, 2, 30), 0, -1, 0)); // Feb 29, 2020

Note that this works even if you go past the end of the month or year.

请注意,即使您已经过了月末或年末,这也有效。

Update:As the example above shows, this has been updated to handle variances in the number of days in a month.

更新:如上例所示,此更新已更新以处理一个月中天数的差异。

回答by Younes Henni

Use the moment.jslibrary for time and date management.

使用moment.js库进行时间和日期管理。

import moment = require('moment');

const now = moment();

now.subtract(7, 'seconds'); // 7 seconds ago
now.subtract(7, 'days');    // 7 days and 7 seconds ago
now.subtract(7, 'months');  // 7 months, 7 days and 7 seconds ago
now.subtract(7, 'years');   // 7 years, 7 months, 7 days and 7 seconds ago
// because `now` has been mutated, it no longer represents the current time

回答by Stefano Borzì

I implemented a function similar to the momentjsmethod subtract.

我实现了一个类似于momentjs方法减法的函数。

- If you use Javascript

- 如果您使用 Javascript

function addDate(dt, amount, dateType) {
  switch (dateType) {
    case 'days':
      return dt.setDate(dt.getDate() + amount) && dt;
    case 'weeks':
      return dt.setDate(dt.getDate() + (7 * amount)) && dt;
    case 'months':
      return dt.setMonth(dt.getMonth() + amount) && dt;
    case 'years':
      return dt.setFullYear( dt.getFullYear() + amount) && dt;
  }
}

example:

例子:

let dt = new Date();
dt = addDate(dt, -1, 'months');// use -1 to subtract 

- If you use Typescript:

- 如果您使用打字稿:

export enum dateAmountType {
  DAYS,
  WEEKS,
  MONTHS,
  YEARS,
}

export function addDate(dt: Date, amount: number, dateType: dateAmountType): Date {
  switch (dateType) {
    case dateAmountType.DAYS:
      return dt.setDate(dt.getDate() + amount) && dt;
    case dateAmountType.WEEKS:
      return dt.setDate(dt.getDate() + (7 * amount)) && dt;
    case dateAmountType.MONTHS:
      return dt.setMonth(dt.getMonth() + amount) && dt;
    case dateAmountType.YEARS:
      return dt.setFullYear( dt.getFullYear() + amount) && dt;
  }
}

example:

例子:

let dt = new Date();
dt = addDate(dt, -1, 'months'); // use -1 to subtract

Optional (unit-tests)

可选(单元测试)

I also made some unit-tests for this function using Jasmine:

我还使用Jasmine为这个函数做了一些单元测试:

  it('addDate() should works properly', () => {
    for (const test of [
      { amount: 1,  dateType: dateAmountType.DAYS,   expect: '2020-04-13'},
      { amount: -1, dateType: dateAmountType.DAYS,   expect: '2020-04-11'},
      { amount: 1,  dateType: dateAmountType.WEEKS,  expect: '2020-04-19'},
      { amount: -1, dateType: dateAmountType.WEEKS,  expect: '2020-04-05'},
      { amount: 1,  dateType: dateAmountType.MONTHS, expect: '2020-05-12'},
      { amount: -1, dateType: dateAmountType.MONTHS, expect: '2020-03-12'},
      { amount: 1,  dateType: dateAmountType.YEARS,  expect: '2021-04-12'},
      { amount: -1, dateType: dateAmountType.YEARS,  expect: '2019-04-12'},
    ]) {
      expect(formatDate(addDate(new Date('2020-04-12'), test.amount, test.dateType))).toBe(test.expect);
    }

  });

To use this test you need this function:

要使用此测试,您需要此功能:

// get format date as 'YYYY-MM-DD'
export function formatDate(date: Date): string {
  const d     = new Date(date);
  let month   = '' + (d.getMonth() + 1);
  let day     = '' + d.getDate();
  const year  = d.getFullYear();

  if (month.length < 2)  {
    month = '0' + month;
  }
  if (day.length < 2) {
    day = '0' + day;
  }

  return [year, month, day].join('-');
}

回答by Alan Gee

This does not answer the question fully, but for anyone who is able to calculate the number of days by which they would like to offset an initial date then the following method will work:

这并不能完全回答这个问题,但是对于任何能够计算出他们想要抵消初始日期的天数的人来说,以下方法将起作用:

myDate.setUTCDate(myDate.getUTCDate() + offsetDays);

offsetDays can be positive or negative and the result will be correct for any given initial date with any given offset.

offsetDays 可以是正数或负数,对于任何给定的初始日期和任何给定的偏移量,结果都是正确的。