Получить объект даты (шесть месяцев назад) из другого объекта даты - PullRequest
11 голосов
/ 30 октября 2009

Как я могу создать объект даты , который меньше n количества месяцев от другого объекта даты ? Я ищу что-то вроде DateAdd().

Пример:

var objCurrentDate = new Date();

Теперь, используя objCurrentDate, как я могу создать объект Date, дата которого на шесть месяцев старше сегодняшней даты / objCurrentDate?

Ответы [ 3 ]

32 голосов
/ 30 октября 2009

Вы можете очень легко реализовать функцию "addMonths" :

function addMonths(date, months) {
  date.setMonth(date.getMonth() + months);
  return date;
}


addMonths(new Date(), -6); // six months before now
// Thu Apr 30 2009 01:22:46 GMT-0600 

addMonths(new Date(), -12); // a year before now
// Thu Oct 30 2008 01:20:22 GMT-0600
1 голос
/ 30 октября 2009
var oldDate:Date = new Date();
/*
 Check and adjust the date -
 At the least, make sure that the getDate() returns a 
 valid date for the calculated month and year.
 If it's not valid, change the date as per your needs.
 You might want to reset it to 1st day of the month/last day of the month
 or change the month and set it to 1st day of next month or whatever.
*/
if(oldDate.getMonth() < n)
    oldDate.setFullYear(oldDate.getFullYear() - 1);
oldDate.setMonth((oldDate.getMonth() + n) % 12);
0 голосов
/ 04 января 2017

Создайте объект даты и передайте значение n, где n - число (добавление / добавление) месяца.

  var dateObj = new Date();
  var requiredDate= dateObj.setMonth(dateObj.getMonth() - n);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...