Skip to content

Instantly share code, notes, and snippets.

@kevin-isky
Last active October 8, 2022 03:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevin-isky/660b3b7b84c7adb82f38 to your computer and use it in GitHub Desktop.
Save kevin-isky/660b3b7b84c7adb82f38 to your computer and use it in GitHub Desktop.
Javascript计算月份中的天数

根据年份和月份计算出该月份有多少天?2月的天数和是否闰年有关系,其他的月份天数是固定的,本来要考虑自己写代码去实现该功能,网上发现了更为简洁优雅的办法:

// Month is 1 based
function daysInMonth(month,year) {
	return new Date(year, month, 0).getDate();
}

测试下结果如何:

// July
daysInMonth(7,2009); //31
// February
daysInMonth(2,2009); //28
daysInMonth(2,2008); //29

关于这种实现方法的原理解释:

Day 0 is the last day in the previous month. Because the month constructor is 0-based, this works nicely.

需要注意的是javascript中的月份是0-based的,2代表3月份,因此new Date(2009, 2, 0).getDate()计算的是2月份的天数。

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment