EDIT: I just made a jsfiddle to demonstrate the problem here: http://jsfiddle.net/GvjRd/3/
I have a web tool that uses the JQuery UI datepicker. It has been working smoothly for weeks, but then all of a sudden it stopped working today. No matter what day/month/year I pick on the calendar, when I select a day and call alert(currentTime.getMonth()); it returns ‘7’. It returns the day/year just fine.
I proceeded to test just the datepicker on its own, making a very simple page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<link type="text/css" href="ui-lightness/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
<link rel="stylesheet" href="demos.css">
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.21.custom.min.js"></script>
<script type="text/javascript">
$(function() {
$("#datepicker").datepicker({
onSelect : function(dateText, inst) {
var currentTime = new Date();
currentTime.setDate($("#datepicker").datepicker("getDate").getDate());
alert(currentTime.getMonth());
}
});
});
</script>
</head>
<body>
Date:
<input type="text" id="datepicker">
</body>
Even on this page, no matter what day/month/year combination I choose, the alert says ‘7’. Anyone else having this problem?
Months in JavaScript are zero based so 7 = the 8th month, or August.
In your example, you’re setting the
currentTimeto today and then only changing the day of that date object to the date picked on the calendar, leaving the month and year unchanged. Therefore,currentTime.getMonth()will always show the month that the running the script in, not the date picked from the calendar. To do that, usecurrentTime.setMonth($("#datepicker").datepicker("getDate").getMonth());jsFiddle example