如何使用javascript按季度添加月份

时间:2011-05-07 14:35:28

标签: javascript jquery

特此我有以下输入:

分隔的月份:4个月

将包含月份和年份的日期:07-05-2011。

现在我需要使用java脚本或jquery将月数加4。怎么办呢?

例如:

我的日期为:01-01-2011,持续时间为4

我的输出应为:

2010年1月12日

01-04-2011

2011年1月8日

01-12-2011

例如,如果是:

我的日期为:01-06-2011,持续时间为4

我的输出应为:

01-06-2011

2011年1月10日

01-02-2012

2012-06-01

提前致谢

4 个答案:

答案 0 :(得分:3)

你有:

var initialDate = new Date(2011, 5, 1); //Your example number two. January is 0
for(var i=0; i<4; i++){
  var newMonth = initialDate.getMonth() + i;
  var newYear = initialDate.getYear();
  if(newMonth >= 12){
     newMonth = newMonth % 12;
     newYear ++;
  }
  var newDate = new Date(newYear, newMonth, 1);
  alert(newDate);
}

希望这会有所帮助。干杯

答案 1 :(得分:1)

Date对象有一个getMonth方法和一个setMonth方法,它接受一个整数(月数)。

所以也许是一个功能:

function GetNextPeriod(basisDate){
  // Copy the date into a new object
  var basisDate = new Date(basisDate);
  // get the next month/year
  var month = basisDate.getMonth() +4;
  var year = basisDate.getFullYear();
  if (month >= 12){
    month -= 12;
    year++;
  }
  // set on object
  basisDate.setMonth(month);
  basisDate.setFullYear(year);
  // return
  return basisDate;
}

var period1 = GetNextPeriod(inputDate);
var period2 = GetNextPeriod(period1);
var period3 = GetNextPeriod(period2);

答案 2 :(得分:0)

本机Date对象中没有内置任何日期算术可以像这样做。您可以选择编写自己的函数来添加4个月内的毫秒数,也可以查看DateJS

答案 3 :(得分:0)

这是一个函数,它接受类似01-06-2011的字符串,将其转换为日期变量,添加四个月,并以相同的dd-mm-yyyy格式将结果作为字符串返回:

function addFourMonths(dateString) {
    var dateParts = dateString.split('-');
    var newDate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
    newDate.setMonth(newDate.getMonth() + 4);
    return newDate.getDate() + '-' + (newDate.getMonth() + 1) + '-' + newDate.getFullYear();
}

使用:

var myDate = addFourMonths('01-12-2011');
alert('The date is ' + myDate);

结果(live demo):

'The date is 1-4-2012.'

请注意,如果setMonth(newmonth)大于12,则使用newmonth时会自动增加年份,因此无需对此进行测试,因为此处提供的其他一些答案都可以。

来自MDC docs for setMonth

  

“如果您指定的参数超出预期范围,则setMonth会尝试相应地更新Date对象中的日期信息。例如,如果对monthValue使用15,则年份将增加1(年+ 1) ),和3将用于一个月。“