2015-03-31 145 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())) 
相關問題