【问题标题】:How to add no of days as well as month to specific date?如何将天数和月份添加到特定日期?
【发布时间】:2017-06-16 06:51:23
【问题描述】:

我有一个日期,例如 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");

它给了我错误“无效日期”。代码有什么问题?

【问题讨论】:

  • 更改var rootDate = new Date("31 May,2017")
  • 如果你想使用日期,我建议你看看momentjs.com
  • @sachila 谢谢你..它可以增加 2 天,但不能增加 18 个月..

标签: jquery angularjs date add


【解决方案1】:

首先,将日期转换为 Date 对象

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>

【讨论】:

    【解决方案2】:

    使用这个
    1:用于添加天数moment().add(2,'days').format('DD MMMM, YYYY');
    2:加月份moment().add(18,'months').format('DD MMMM, YYYY');;

    【讨论】:

      【解决方案3】:

      我已经修改了你的代码以这样的方式工作,# 将带来你想要实现的目标。

          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));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-10
        • 2011-06-06
        • 1970-01-01
        • 2021-04-26
        相关资源
        最近更新 更多