[英]get number of days in the CURRENT month using javascript
對於我的網站,我試圖獲取某個功能當前月份的天數。
我在網上看到過獲取指定月份天數的示例,但是我需要獲取當前月份的天數並找出該月還剩多少天。
這是我設法放在一起的代碼:
function myFunction() {
var today = new Date();
var month = today.getMonth();
console.log(month);
}
myFunction();
這是你想要的嗎?
function daysInThisMonth() {
var now = new Date();
return new Date(now.getFullYear(), now.getMonth()+1, 0).getDate();
}
基於這篇文章的答案: 使用 javascript 確定一個月中的天數的最佳方法是什么?
修改它以適用於本月應該很容易 這是您的代碼和另一篇文章中的函數:
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();
請注意,函數date.getMonth()
返回一個從零開始的數字,因此只需加 1 即可標准化。
var numberOfDaysOnMonth = function() {
let h = new Date()
h.setMonth(h.getMonth() + 1)
h.setDate(h.getDate() - 1)
return h.getDate()
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.