2017-06-16 165 views
1

我有一個約會像2017年5月31日。有了這個日期,我需要再添加2天。 然後另一個要求,在同一天我需要增加18個月。 我試過下面的代碼。如何添加日期以及月份到特定日期?

var rootDate = 31 May,2017; 
var firstDate = new Date(); 
var lastDate = new Date(); 

var tempdate = firstDate.setDate(rootDate.getDate() +2); 
firstDate = $filter('date')(tempdate , "dd MMM, yyyy"); 

var tempDateTwo = lastDate.setDate(rootDate.getMonth() +18); 
secondDate = $filter('date')(tempDateTwo , "dd MMM, yyyy"); 

它給我錯誤'無效日期'。代碼中有什麼問題?

+1

變化'VAR rootDate =新的日期( 「2017年5月31日」)' –

+1

如果你想約會的工作,我建議你看一看https://momentjs.com/ –

+0

@sachila謝謝爲此..它正在增加2天,而不是增加18個月的工作.. – Mathi

回答

0

第一,日期轉換日期對象

var rootDate = new Date("31 May,2017");

並設置月份使用setMonth方法

lastDate.setMonth(rootDate.getMonth() +18);

angular.module("app",[]) 
 
.controller("ctrl",function($scope,$filter){ 
 
var rootDate = new Date("31 May,2017"); 
 
var firstDate = new Date(); 
 
var lastDate = new Date(); 
 

 
var tempdate = firstDate.setDate(rootDate.getDate() +2); 
 
firstDate = $filter('date')(tempdate , "dd MMM, yyyy"); 
 
console.log(firstDate) 
 

 
var tempDateTwo = lastDate.setMonth(rootDate.getMonth() +18); 
 
lastDate = $filter('date')(tempDateTwo , "dd MMM, yyyy"); 
 
console.log(lastDate) 
 

 
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="ctrl"> 
 
    
 
</div>

0

使用此
1:用於添加天moment().add(2,'days').format('DD MMMM, YYYY');
2:對於添加月moment().add(18,'months').format('DD MMMM, YYYY');;

0

我修改了你的代碼以這種方式工作,#會帶來你想達到的目標。

var rootDate = '31 May,2017'; 
    var firstDate = new Date(rootDate); 
    var lastDate = new Date(rootDate); 

    firstDate.setDate(firstDate.getDate() + parseInt(2));  

    lastDate.setMonth(lastDate.getMonth() + parseInt(18)); 
相關問題