JS獲取月份最后天數、最大天數與某日周數的方法
本文實例講述了JS獲取月份最后天數、最大天數與某日周數的方法。分享給大家供大家參考,具體如下:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>標題頁</title>
<script language="javascript">
function getLastDay(year,month)
{
var new_year = year; //取當前的年份
var new_month = month++;//取下一個月的第一天,方便計算(最后一天不固定)
if(month>12) //如果當前大于12月,則年份轉到下一年
{
new_month -=12; //月份減
new_year++; //年份增
}
var newnew_date = new Date(new_year,new_month,1);//取當年當月中的第一天
return (new Date(new_date.getTime()-1000*60*60*24)).getDate();//獲取當月最后一天日期
}
</script>
<body>
<input id="Button1" type="button" value="取2007年5月的最后一天" onClick="alert(getLastDay(2007,5))" />
</body>
</html>
js得到一個月最大天數
JS里 面的new Date("xxxx/xx/xx")這個日期的構造方法有一個妙處,
當你傳入的是"xxxx/xx/0"(0號)的話,得到的日期是"xx"月的前一個 月的最后一天("xx"月的最大取值是69,題外話),
當你傳入的是"xxxx/xx/1"(1號)的話,得到的日期是"xx"月的后一個 月的第一天(自己理解)
如果傳入"1999/13/0",會得到"1998/12/31"。而且最大的好處是當你傳入"xxxx/3/0",會得到xxxx年2月的最后一天,它會自動判斷當年是否是閏年來返回28或29,不用自己判斷,
所以,我們想得到選擇年選擇月有多少天的話,只需要
var temp=new Date("選擇年/選擇月+1/0");
return temp.getDate()//最大天數
校驗的話,也可以用這個方法。
下面是使用JS編寫的獲取某年某月有多少天的getDaysInMonth(year, month)方法:
function getDaysInMonth(year,month){
month = parseInt(month,10)+1;
var temp = new Date(year+"/"+month+"/0");
return temp.getDate();
}
js 獲取某年的某天是第幾周
/**
* 判斷年份是否為潤年
*
* @param {Number} year
*/
function isLeapYear(year) {
return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
}
/**
* 獲取某一年份的某一月份的天數
*
* @param {Number} year
* @param {Number} month
*/
function getMonthDays(year, month) {
return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] || (isLeapYear(year) ? 29 : 28);
}
/**
* 獲取某年的某天是第幾周
* @param {Number} y
* @param {Number} m
* @param {Number} d
* @returns {Number}
*/
function getWeekNumber(y, m, d) {
var now = new Date(y, m - 1, d),
year = now.getFullYear(),
month = now.getMonth(),
days = now.getDate();
//那一天是那一年中的第多少天
for (var i = 0; i < month; i++) {
days += getMonthDays(year, i);
}
//那一年第一天是星期幾
var yearFirstDay = new Date(year, 0, 1).getDay() || 7;
var week = null;
if (yearFirstDay == 1) {
week = Math.ceil(days / yearFirstDay);
} else {
days -= (7 - yearFirstDay + 1);
week = Math.ceil(days / 7) + 1;
}
return week;
}
希望本文所述對大家JavaScript程序設計有所幫助。
相關文章
初學js插入節(jié)點appendChild insertBefore使用方法
由于可見insertBefore()方法的特性是在已有的子節(jié)點前面插入新的節(jié)點但是兩種情況結合起來發(fā)現insertBefore()方法插入節(jié)點,是可以在子節(jié)點列表的任意位置。2011-07-07

