代码之家  ›  专栏  ›  技术社区  ›  Shyju

从另一个日期对象获取日期对象(六个月前)

  •  11
  • Shyju  · 技术社区  · 16 年前

    如何创建 日期对象 小于 n 与另一个月的月数 日期对象 ?我在找类似的东西 DateAdd() .

    例子:

    var objCurrentDate = new Date();
    

    现在使用 objCurrentDate ,如何创建 Date 对象的日期比今天的日期早6个月/ 对象当前日期 ?

    3 回复  |  直到 9 年前
        1
  •  32
  •   Christian C. Salvadó    16 年前

    您可以很容易地实现 “加月” 功能:

    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
    
        2
  •  1
  •   Peter Mortensen Pieter Jan Bonestroo    16 年前
    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);
    
        3
  •  0
  •   Ankit    9 年前

    创建日期对象并传递n的值,其中n是月份的数字(加/减)。

      var dateObj = new Date();
      var requiredDate= dateObj.setMonth(dateObj.getMonth() - n);