【问题标题】:CalendarExtender saying the wrong date is selected, possibly timezone relatedCalendarExtender 说选择了错误的日期,可能与时区有关
【发布时间】:2013-05-03 00:09:07
【问题描述】:

我有一个带有TextBoxCalendarExtender 的页面,应该可以让我检测选择的日期。但是,这是报告未选择的日期。

<asp:TextBox ID="tbEffectiveDate" runat="server"
    CssClass="input-small"
    MaxLength="10"
    Text='<%# Bind("NewEffectiveDate", "{0:MM/dd/yyyy}") %>'>
</asp:TextBox>
<ajaxToolkit:CalendarExtender ID="atkEffectiveDate" runat="server"
    FirstDayOfWeek="Sunday"
    TargetControlID="tbEffectiveDate"
    Format="MM/dd/yyyy"
    OnClientDateSelectionChanged="CheckForSunday">
</ajaxToolkit:CalendarExtender>

基本上我是在确保用户选择了星期天,但是当我在日历上选择一天时,JavaScript 会说它是前一天。我很困惑。

function CheckForSunday(sender, args) {
    var selectedDate = new Date();
    selectedDate = sender.get_selectedDate();
    // Both of these show the date before the date was selected
    alert(sender.get_selectedDate());

    if (selectedDate.getDay() != 0) {
        // not a Sunday
        var sunday = selectedDate;
        // calculated the nearest Sunday
        sunday.setDate(selectedDate.getDate() - selectedDate.getDay());
        sender.set_selectedDate(sunday);
        // tell the user that the date wasn't a Sunday
        // and that the previous Sunday was selected.
        $("#must-be-sunday").modal("show");
    }
}

例如,如果我选择一个星期日,比如 5 月 5 日:

然后在alert(sender.get_selectedDate());这一行显示

这表示选择了 5 月 4 日星期六而不是 5 月 5 日。由于在我的语言环境中,我们是 -0700,并且显示的是 5 日午夜前 7 小时,我猜这与时区有关。

有谁知道可能导致此问题的原因以及如何解决它,使其不适用于时间和仅选择的日期?

【问题讨论】:

    标签: javascript asp.net ajaxcontroltoolkit ajax.net


    【解决方案1】:

    你说得对,因为 CalendarExtender 的时区问题对每一天的单元格值使用 UTC 日期。如果您想检查所选的星期几,您可以在 OnClientDateSelectionChanged 处理程序中使用 Date.getUTCDay() 函数而不是 Date.getDay()getUTCDate() 而不是 getDate()

    【讨论】:

      【解决方案2】:

      像往常一样,在这里将所有内容写成问题后,我已经解决了我的问题。这确实是由于时区,但仍然很尴尬。如果有人有更好的解决方案,我很乐意听到。

      使用getTimezoneOffset()How to add 30 minutes to a JavaScript Date object? 的解决方案,我创建了一个计算来解决这个问题。

      var selectedDate = sender.get_selectedDate();
      // get the timezone offset in minutes
      var timeOffsetMinutes = selectedDate.getTimezoneOffset();
      // Convert minutes into milliseconds and create a new date based on the minutes.
      var correctedDate = new Date(selectedDate.getTime() + timeOffsetMinutes * 60000);
      

      这更正了我的问题,我得到了所需的日期。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-27
        相关资源
        最近更新 更多