【问题标题】:Increment Month in JavaScript removes the DATE format using setMonth() [duplicate]JavaScript 中的 Increment Month 使用 setMonth() 删除 DATE 格式 [重复]
【发布时间】:2018-11-28 15:09:57
【问题描述】:

以下是我的 JavaScript 代码,用于尝试创建一个用户无法在未来这么多月内预订的最大日期:

var x= 12;
var arriveDate = "28/11/2018"
var currentDate = new Date();
var a_date = new Date(arriveDate);
var max_month = currentDate.setMonth(currentDate.getMonth()+ x);

if (arriveDate === ""){
        $("#arrive_date_error").html("Please don't leave this field blank");
    }
    else if (a_date < currentDate){
        console.log("Please don't select a date in the past")
    }
    else if (a_date > max_month){
        console.log("date in future")
    }

无论我尝试什么月/日/年,最后一个 else if 似乎都不起作用。我决定使用 console.log(max_month) 查看它创建的月份并返回: 1574953488195 而不是正确的格式: 2019 年 11 月 28 日星期四 15:04:48 GMT+0000

我做错了什么,为什么在我尝试更改日期对象的月份时会更改格式?

【问题讨论】:

  • "28/11/2018" 不是 ECMA-262(或我知道的任何实现)支持的格式。这可能会导致日期无效,或日期为 2020 年 4 月 11 日。或其他。

标签: javascript validation date format


【解决方案1】:

setMonth 改变了currentDate,它不返回新的日期。您可能想要克隆日期并设置克隆日期的月份:

 var max_month = new Date(+currentDate);
 max_month.setMonth(max_month.getMonth() + x);

【讨论】:

  • "...它既不返回新日期也不返回其他日期" - .setMonth() 返回 1970 年 1 月 1 日之间的毫秒数00:00:00 UTC 和更新日期。
  • 这对我有用,谢谢。为了在未来获得 x 个月,这是最好的解决方案吗?
  • @cameronWard 是的,至少它适用于所有情况。从长远来看,您可能想看看 momentJS,因为它更易于使用。
  • new Date(currentDate) 很可能返回无效日期。随后对 set/getMonth 的调用不会改变它,它仍然是一个无效的日期。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-01
  • 2021-11-09
  • 2011-11-28
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多