Javascript 使用javascript获取当前月份的天数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38446725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get number of days in the CURRENT month using javascript
提问by Khan
For my website I am trying to get the number of days for the CURRENT month for a certain feature.
对于我的网站,我试图获取某个功能当前月份的天数。
I have seen examples online that get days of a specified month, however I need to get the days of the CURRENT month and find how many days are left of that month.
我在网上看到过获取指定月份天数的示例,但是我需要获取当前月份的天数并找出该月还剩多少天。
Here is the code I managed to put together:
这是我设法放在一起的代码:
function myFunction() {
var today = new Date();
var month = today.getMonth();
console.log(month);
}
myFunction();
回答by user94559
Does this do what you want?
这是你想要的吗?
function daysInThisMonth() {
var now = new Date();
return new Date(now.getFullYear(), now.getMonth()+1, 0).getDate();
}
回答by Peter
based on the answer from this post: What is the best way to determine the number of days in a month with javascript?
基于这篇文章的答案: 使用 javascript 确定一个月中的天数的最佳方法是什么?
It should be easy to modify this to work for the current month Here's your code and the function from the other post:
修改它以适用于本月应该很容易 这是您的代码和另一篇文章中的函数:
function myFunction() {
var today = new Date();
var month = today.getMonth();
console.log(daysInMonth(month + 1, today.getFullYear()))
}
function daysInMonth(month,year) {
return new Date(year, month, 0).getDate();
}
myFunction();
Note that the function date.getMonth()
returns a zero-based number, so just add 1 to normalize.
请注意,该函数date.getMonth()
返回一个从零开始的数字,因此只需加 1 即可标准化。