问题
I have this javascript for automatically setting a date filter to the first and last day of the previous month:
$(document).ready(function () {
$("#DateFrom").datepicker({ dateFormat: 'dd/mm/yy' });
$("#DateTo").datepicker({ dateFormat: 'dd/mm/yy' });
var now = new Date();
var firstDayPrevMonth = new Date(now.getYear(), now.getMonth() - 1, 1);
var firstDayThisMonth = new Date(now.getYear(), now.getMonth(), 1);
var lastDayPrevMonth = new Date(firstDayThisMonth - 1);
$("#DateFrom").datepicker("setDate", firstDayPrevMonth);
$("#DateTo").datepicker("setDate", lastDayPrevMonth);
});
BUT now.getYear() is returning 111 instead of the expected 2011. Is there something obvious I've missed?
回答1:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getYear
getYearis no longer used and has been replaced by thegetFullYearmethod.The
getYearmethod returns the year minus 1900; thus:
- For years greater than or equal to 2000, the value returned by
getYearis 100 or greater. For example, if the year is 2026,getYearreturns 126.- For years between and including 1900 and 1999, the value returned by
getYearis between 0 and 99. For example, if the year is 1976,getYearreturns 76.- For years less than 1900, the value returned by
getYearis less than 0. For example, if the year is 1800,getYearreturns -100.- To take into account years before and after 2000, you should use
getFullYearinstead ofgetYearso that the year is specified in full.
回答2:
In order to comply with boneheaded precedent, getYear() returns the number of years since 1900.
Instead, you should call getFullYear(), which returns the actual year.
回答3:
From what I've read on Mozilla's JS pages, getYear is deprecated. As pointed out many times, getFullYear() is the way to go. If you're really wanting to use getYear() add 1900 to it.
var now = new Date(),
year = now.getYear() + 1900;
来源:https://stackoverflow.com/questions/4754938/javascript-date-getyear-returns-111-in-2011