Javascript创建不存在的日期

Javascript creates dates that dont exist

本文关键字:日期 不存在 创建 Javascript      更新时间:2023-09-26

我写了一些JS来尝试并提出用户选择的月份的最后日期,我试图弄清楚为什么它会提出不存在的日期,例如6/31/2015,问题可能是围绕我如何计算月末,但我只是看不到我的方式在这里得出正确的结论。这是一个有趣的bug,所以我想看看你们是否有解决方案。

var ealiest_effective_date = new Date(Date.parse("#{ruby_earliest_time_which_is_confirmed_correct.try(:strftime, "%m/%d/%Y")}"));
var minimumtime = Date.parse(new Date(ealiest_effective_date.getFullYear(), ealiest_effective_date.getMonth() + 2, 0));
$('.selected-date').change(function (e) {
    date = Date.parse($(this).val());
    user_selected_date = new Date(date);
    console.log(user_selected_date.getMonth()+'/'+user_selected_date.getDate()+'/'+user_selected_date.getFullYear());
    var possibleResultantEndOfMonth = Date.parse(new Date(user_selected_date.getFullYear(), user_selected_date.getMonth() + 2, 0));
    var terminationEndOfMonth = new Date(Math.max(possibleResultantEndOfMonth,minimumtime));
    var end_of_month_date = terminationEndOfMonth.getMonth()+'/'+terminationEndOfMonth.getDate()+'/'+terminationEndOfMonth.getFullYear();
    $('#should_be_end_of_month').val(effective_date);
 });

.getMonth() JavaScript方法返回月份作为从零开始的值。1月是0,12月是11。在你的例子中,6/31/2015实际上应该是7月31日,而不是6月

我也要小心下面的代码

date = Date.parse($(this).val());

对于不同地区设置的人可能不起作用。

我不知道你的逻辑或计算,但在JavaScript中使用日期时,我强烈建议使用Moment.js,它允许以一种简单的方式进行日期操作,也允许处理时区。看一看,我想它会对你有帮助的。

d = moment("20150231", "YYYYMMDD")
d.isValid()
false
moment("20150228", "YYYYMMDD").isValid()
true

除非您之前声明过,否则您的变量为:

var ealiest_effective_time

但是你引用的是:

ealiest_effective_date