2015-03-31 150 views
0

Iam通过使用下面的代码将6个月添加到今天的日期。通过将6个月添加到今天的日期获取月份的最后日期

var d = new Date(); 
     var curr_date = d.getDate(); 
     var curr_month = d.getMonth() + 7; //Months are zero based 
     if(curr_month<10){ 
      curr_month = "0"+curr_month; 
     } 
     if(curr_date<10){ 
      curr_date = '0'+curr_date; 
     } 
     var curr_year = d.getFullYear(); 
     $scope.vmEndDate = curr_year + "/" + curr_month + "/" + curr_date; 

当我打印$ scope.vmEndDate值,荫得到2015年9月31日,但在9月当月31天是不存在的。如何获得正确的价值。

+1

首先,您必须确定“正确”的值实际上是什么。 – user3710044 2015-03-31 11:47:02

+0

在上面的代码curr_date是今天的日期(2015年3月31日),所以当添加6个月到这个日期Iam获取2015/09/31,这是错误的日期,因为32天不存在。 – Lakshmi 2015-03-31 11:52:49

回答

2

您可以处理日期直接与月:

var today = new Date(2015,03,31) 
today.setMonth(today.getMonth()+6) 
console.log(today.toLocaleDateString()) 

如果你想获得一个有效的日期,但在九月,https://stackoverflow.com/a/11469976/4682796

+0

通过使用上面的代码我得到2015年11月1日上午12:00:00,但它显示11月份 – Lakshmi 2015-03-31 12:03:32

+0

http://stackoverflow.com/a/11469976/4682796 – jmgross 2015-03-31 12:09:05

0

在JavaScript的世界个月开始的零!对我来说有点奇怪。无论如何,增加7个日期不是9月,而是7个是10月。

因此,这意味着你的代码是正确的

只要改变

var curr_month = d.getMonth() + 7; //Months are zero based 

var curr_month = d.getMonth() + 6; //Months are zero based 
0

下面的代码片段可能会有所帮助。

var d = new Date(); 
var curr_date = new Date(d.getFullYear(), d.getMonth() + 6, d.getDate()); 
console.log(curr_date.getFullYear() + "/" + 
((curr_date.getMonth() + 1).toString().length == 1 ? '0' + 
(curr_date.getMonth() + 1) : (curr_date.getMonth() + 1)) + "/" + 
(curr_date.getDate().toString().length == 1 ? '0' + 
(curr_date.getDate()) : (curr_date.getDate()))); 
} 
0

使用来自this question的代码,可以如下解决。 您首先得到今天的日期,将其日期更改为第一天(或任何适用于所有月份的号码,如1至28),然后向前移动六个月,然后将日期设置为该月的最后一天。

function daysInMonth(month, year) 
{ 
    return 32 - new Date(year, month, 32).getDate(); 
} 

var today = new Date() 
today.setDate(1) 
today.setMonth(today.getMonth()+6) 
today.setDate(daysInMonth(today.getMonth(), today.getDate())) 
相关问题