CalendarExtender表示选择了错误的日期,可能与时区有关

时间:2013-05-08 16:55:18

标签: javascript asp.net ajaxcontroltoolkit ajax.net

我有一个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日:

enter image description here

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

enter image description here

这是说周五,5月4日被选中而不是5月5日。因为在我的语言环境中,我们是-0700,这是在5日午夜前7小时显示,我猜这与时区有关。

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

2 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:2)

您说明由于时区而导致的问题,因为CalendarExtender使用每日单元格值的UTC日期。如果您想查看选定的星期几,则可以使用Date.getUTCDay()功能代替Date.getDay()getUTCDate(),而不是getDate()处理程序中的OnClientDateSelectionChanged