javascript
  • asp.net
  • ajaxcontroltoolkit
  • ajax.net
  • 2013-05-08 36 views 4 likes 
    4

    我有一個TextBoxCalendarExtender的頁面,它應該允許我檢測選擇的日期。但是,這是報告未選擇的日期。CalendarExtender表示選擇了錯誤的日期,可能與時區有關

    <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

    你的權利,作爲CalendarExtender時區的問題使用UTC日期爲每一天的單元格值。如果您想檢查選定的星期幾,則可以使用Date.getUTCDay()函數代替Date.getDay()getUTCDate(),而不是getDate()OnClientDateSelectionChanged處理程序中。

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

    這糾正了我的問題,我得到所需的日期。

    相關問題