[英]Get Date of days of a week given year, month and week number (relative to month) in Javascript / Typescript
[英]Javascript: calculate number of days in month for a given year
我有一個HTML頁面,包含月份,日期和年份的3個下拉列表,我想知道是否有辦法根據月份和年份正確填充月份下拉列表。
我之前沒有在客戶端做過這個,但看起來像jQuery DatePicker這樣的很多控件都是在幕后做的。
據我所知,沒有(整潔的)內置功能。 我曾寫過一次:
// note that month is 0-based, like in the Date object. Adjust if necessary.
function getNumberOfDays(year, month) {
var isLeap = ((year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0));
return [31, (isLeap ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
}
您可以使用日期對象:
var monthStart = new Date(year, month, 1);
var monthEnd = new Date(year, month + 1, 1);
var monthLength = (monthEnd - monthStart) / (1000 * 60 * 60 * 24)
使用Date
對象的算術給出了毫秒數。
這甚至適用於12月; Date構造函數通過環繞處理超出范圍的參數。
請注意, month
從零開始(必須介於0
到11
之間)
從另一篇文章復制: 使用javascript獲取指定月份的天數?
//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
所有@c_harm的學分,真的很棒的解決方案
Date.prototype.daysinMonth: function(){
var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();
}
function daysinMonthfromInput(month,year){
return (new Date(year,month-1,1)).daysinMonth();
}
alert(daysinMonthfromInput(2,2011));
這是一個班輪。 假設您說的是1月= 1,2月= 2等...(正常)這是閏年示例:
var y = 2012;
var m = 2;
var daysInMonth = new Date(y,m,1,-1).getDate();
我在我當前的項目中使用這種方法,發現我需要正確的舍入錯誤。 因此,我不必在代碼中使用monthLength,而是使用它:
monthLength.toFixed(0)
例如,如果我有一個對象,我在其中存儲文本日期字段,它可能如下所示:
obj.month = theMonths[mm - 1] + " " + monthLength.toFixed(0) + ", " + obj.year;
你實際上可以使用這個:
var curdate = new Date(); DaysMonth = 32 - new Date(curdate.getYear(),curdate.getMonth(),32)。getDate();
;)
Date.prototype.daysinMonth= function(){
var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();
};
function daysinMonthfromInput (month, year) {
return (new Date(year, month - 1, 1)).daysinMonth();
};
function fillallday (elem, month, year) {
var options = null;
var elementExists = document.getElementById(elem);
if (elementExists != null) {
this.removeOptions(elementExists);
var opt = document.createElement('option');
opt.value = "";
opt.innerHTML = "---Day---";
elementExists.appendChild(opt);
if (month != "") {
if (typeof (year) === "undefined") {
year = new Date().getFullYear();
}
if (year == "") {
year = new Date().getFullYear();
}
var days = daysinMonthfromInput(month, year);
for (var i = 1; i <= days; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
elementExists.appendChild(opt);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.