【问题标题】:get the month last date by adding 6 months to today's date通过将 6 个月添加到今天的日期来获取上个月的日期
【发布时间】:2015-03-31 11:44:03
【问题描述】:

我正在使用以下代码将今天的日期加上 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/09/31 ,但在 9 月的第 31 天不存在。如何获得正确的值。

【问题讨论】:

  • 首先您必须确定“正确”值实际上是什么。
  • 在上面的代码中 curr_date 是今天的日期(03/31/2015),所以当我得到 2015/09/31 的这个日期加上 6 个月时,这是错误的日期,因为 32 天不存在。

标签: javascript angularjs


【解决方案1】:

您可以直接处理带有月份的日期:

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

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

【讨论】:

  • 通过使用上面的代码,我得到了 2015 年 11 月 1 日凌晨 12:00:00,但它显示的是 11 月
【解决方案2】:

在 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

【讨论】:

    【解决方案3】:

    以下代码 sn-p 可能会有所帮助。

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

    【讨论】:

      【解决方案4】:

      使用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()))
      

      【讨论】:

        猜你喜欢
        • 2016-03-28
        • 2018-12-19
        • 2019-07-10
        • 1970-01-01
        • 2013-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多