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();
Does this do what you want?
function daysInThisMonth() {
var now = new Date();
return new Date(now.getFullYear(), now.getMonth()+1, 0).getDate();
}
based on the answer from this post: What is the best way to determine the number of days in a month with 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.
var numberOfDaysOnMonth = function() {
let h = new Date()
h.setMonth(h.getMonth() + 1)
h.setDate(h.getDate() - 1)
return h.getDate()
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.