使用
$('#myDate').datepicker('getDate')
将以更安全的方式为您获取 JavaScript 日期对象。此外,getMonth() 将返回索引为零的月份,因此 July 将返回为“6”。要返回全年,您应该使用:.getFullYear()
javascript“new Date()”可能没有以正确的日期格式解析它。如果您正确设置了 datepicker 的日期形式,那么当您使用它的 'getDate' 方法时,小部件将为您完成工作。
因此,您的代码将变为:
var date = $("#myDate").datepicker('getDate');
alert(date.getDate()); // Day of the month
alert(date.getMonth()); // Month with a zero index
alert(date.getDay()); // Day of the week
alert(date.getFullYear()); // The "full" year, e.g. 2011
// 更新了选择列表的解决方案
从下拉列表中选择正确的值很大程度上取决于您设置值的方式。即如果值是:
<select id="MySelect">
<option value="1">Jan</option>
</select>
那么你可以这样做:
$('#MySelect').val((date.getMonth() + 1));
这将选择指定的月份。但是,如果您的值是月份名称的某种变体,即:
<select id="MySelect">
<option value="Jan">Jan</option>
</select>
然后你需要一个函数来将月份编号映射到它的名称,例如:
var months = ['Jan', 'Feb', 'Mar', ...etc }
function getMonthShortName(month) {
return months[month];
}
$('#MySelect').val(getMonthShortName(date.getMonth()));