I have a jquery datepicker that formats the date in dd/mm/yyyy. I need to display the month name when someone types in a date, a date is selected and on load. i'm struggling to get the month. myDate is the textbox attached to the datepicker. i have this:
var date = new Date($("#myDate").val());
alert(date.getDate());
alert(date.getMonth());
alert(date.getDay());
alert(date.getYear());
When i run it with a date of 18/07/2011, i get 5 for the month, 4 for the day, 7 for the date and 112 for the year, which is all very odd. What am i doing wrong? all i need to do is dynamically change a mont开发者_如何学编程h label to the month selected/typed in with the datepicker i.e July...
To get date from datepicker you should use $("#myDate").datepicker("getDate")
. While what you are currently doing builds a JavaScript Date object which probably interprets the .val() in a wrong way.
Using
$('#myDate').datepicker('getDate')
Will get you the JavaScript date object in a safer manner. Additionally, getMonth() will return the month with a zero index, so July will be returned as "6". To return the full year you should use: .getFullYear()
The chances are javascript "new Date()" wasn't parsing it in the correct date format. If you've set the datepicker's date form correctly, then the widget will do the work for you when you use it's 'getDate' method.
Your code would therefore become:
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
// Updated with solution for the select list
Selecting the correct value from a dropdown will depend much on how you have your values set up. i.e. If the values are:
<select id="MySelect">
<option value="1">Jan</option>
</select>
Then you could simply do:
$('#MySelect').val((date.getMonth() + 1));
This would select the specified month. However if your value is some variation of the month name, i.e.:
<select id="MySelect">
<option value="Jan">Jan</option>
</select>
Then you would need a function to map from the month number to it's name, something like:
var months = ['Jan', 'Feb', 'Mar', ...etc }
function getMonthShortName(month) {
return months[month];
}
$('#MySelect').val(getMonthShortName(date.getMonth()));
精彩评论