【问题标题】:Javascripts dateObject: jump from May 31st to next month gets July 1stJavascript 日期对象:从 5 月 31 日跳转到下个月是 7 月 1 日
【发布时间】:2012-07-13 11:49:30
【问题描述】:

我必须为客户端构建一个没有任何库(如 jQuery)的 DatePicker。 我在本地机器上成功了。但是我的客户现在正在使用它,如果它包含在他的网络应用程序中,它会显示一些奇怪的行为。

如果我选择 5 月 31 日并滚动到下个月,我会在 7 月 1 日结束。 在我单击按钮启动“jumpToNextMonth”功能之前,DateObject 实际上是 5 月 31 日。 我假设 dateObject 跳到不存在的 6 月 31 日,然后向前跳到 7 月 1 日。 这也发生在 8 月以及所有其他 30 天的月份,然后是 31 天的月份。

点击时触发的行是

this.currentDate = new Date(this.currentDate.getFullYear(),
                           this.currentDate.getMonth() + 1,
                           this.currentDate.getDate());

我没有在我的本地机器上看到这种行为,也没有看到它运行 apache 服务器。 我无法想象是什么损坏了我的客户网络应用程序上的日期对象,不幸的是我无权访问他们的文件。

如果您能帮我回答这两个问题,我将不胜感激:

  1. 为什么我的本地机器上没有发生这种情况
  2. 如何在不将 Day 设置为“1”的情况下修复它,例如this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() + 1, 1);

我在这里找到了类似的未回答问题 Flex Mobile 4.6: DateSpinner dateAndTime jumping from Jan 31st to March 1st

【问题讨论】:

  • 您已经回答了自己的问题。对象中的 6 月 31 日实际上是 7 月 1 日。

标签: javascript date datepicker monthcalendar


【解决方案1】:

您已经回答了自己的问题。对象中的 6 月 31 日实际上是 7 月 1 日。

这能解决您的问题吗?

function daysInMonth(month, year)
{
    return 32 - new Date(year, month, 32).getDate();
}

var y = this.currentDate.getFullYear();
var m = this.currentDate.getMonth() + 1;
var d = Math.min(this.currentDate.getDate(), daysInMonth(m, y);
this.currentDate = new Date(y, m, d);

【讨论】:

  • 好吧,我实际上找到了为什么它没有发生在我的本地机器上。这在 JavaScript DatePickers 中是如何正常修复的?跳到每个月的 1 号?
  • 我已经编辑了我的帖子。提供的代码能解决您的问题吗?
  • 确实如此,谢谢。虽然我改变了主意,我会跳到每个月的第一天 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多