CalendarExtender, indicating an incorrect date, possibly related to the time zone

I have a page with TextBox and CalendarExtender that should allow me to determine which date is selected. However, this indicates a date that is not selected.

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

Essentially, I'm sure the user chose Sunday, but when I select the day on the calendar, JavaScript says it's the day before. I am perplexed.

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

For example, if I choose Sunday, for example, May 5:

enter image description here

Then in the line alert(sender.get_selectedDate()); is displayed

enter image description here

This says that Saturday, May 4, is chosen instead of May 5. Since in my locale we are -0700, and it shows 7 hours before midnight on the 5th, I assume this has something to do with the time zone.

Does anyone know what could be the reason for this and how to fix it so that it does not work with time and only the selected date is selected?

+4
source share
2 answers

You are correct that the problem is due to time zones, because CalendarExtender uses UTC dates for each value of the day cell. If you want to check the selected day of the week, you can use the Date.getUTCDay() function instead of Date.getDay() and getUTCDate() instead of getDate() in the OnClientDateSelectionChanged handler.

+2
source

As usual, after I wrote everything in the question, I solved the problem. It was indeed due to time zones, but still very uncomfortable. If anyone has a better solution, I would like to hear it.

Using getTimezoneOffset () and the solution of How to add 30 minutes to the date of a JavaScript object? I created a calculation to fix this.

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

This fixed my problem and I got the correct date.

+4
source

Source: https://habr.com/ru/post/1479787/


All Articles