2017-06-16 167 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)); 
相关问题