JavaScript中两个日期之间的月份差异如何计算JavaScript中的两个date()对象的差异,同时只返回差异中的月数?任何帮助都是很好的:)
3 回答
暮色呼如
TA贡献1853条经验 获得超9个赞
function monthDiff(dateFrom, dateTo) { return dateTo.getMonth() - dateFrom.getMonth() + (12 * (dateTo.getFullYear() - dateFrom.getFullYear()))}//examplesconsole.log(monthDiff(new Date(2000, 01), new Date(2000, 02))) // 1console.log(monthDiff(new Date(1999, 02), new Date(2000, 02))) // 12 full yearconsole.log(monthDiff(new Date(2009, 11), new Date(2010, 0))) // 1
January = 0
December = 11
.
忽然笑
TA贡献1806条经验 获得超5个赞
var date1=new Date(2013,5,21);//Remember, months are 0 based in JSvar date2=new Date(2013,9,18);var year1=date1.getFullYear();var year2=date2.getFullYear();var month1=date1.getMonth();var month2=date2.getMonth();if(month1===0){ //Have to take into account month1++; month2++;}var numberOfMonths;
numberOfMonths = (year2 - year1) * 12 + (month2 - month1) - 1;
numberOfMonths = (year2 - year1) * 12 + (month2 - month1);
numberOfMonths = (year2 - year1) * 12 + (month2 - month1) + 1;
紫衣仙女
TA贡献1839条经验 获得超15个赞
function monthDiff(d1, d2) { var months; months = (d2.getFullYear() - d1.getFullYear()) * 12; months -= d1.getMonth() + 1; months += d2.getMonth(); return months <= 0 ? 0 : months;}monthDiff( new Date(2008, 10, 4), // November 4th, 2008 new Date(2010, 2, 12) // March 12th, 2010);// Result: 15: December 2008, all of 2009, and Jan & Feb 2010monthDiff( new Date(2010, 0, 1), // January 1st, 2010 new Date(2010, 2, 12) // March 12th, 2010);// Result: 1: February 2010 is the only full month between themmonthDiff( new Date(2010, 1, 1), // February 1st, 2010 new Date(2010, 2, 12) // March 12th, 2010);// Result: 0: There are no *full* months between them
添加回答
举报
0/150
提交
取消