JS获取时间日期常用方法

时间:2024-04-15 03:22:47

1 当前时间:

new Date()

2 当前周:

function getCurrentWeek() {
var date = new Date()
var beginDate = new Date(date.getFullYear(), 0, 1);
var week = Math.ceil((parseInt((date - beginDate) / (24 * 60 * 60 * 1000)) + 1 + beginDate.getDay()) / 7);
return week;
}

3 当前月(获取的月份值范围为:0-11,0表示1月份):

new Date().getMonth()

4 当前年(注意与getYear的区别):

new Date().getFullYear()

5 当前星期几

function getWeekDate() {
var now = new Date();
var day = now.getDay();
var weeks = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
var week = weeks[day];
return week;
}

6 日期格式化

Date.prototype.format = function (fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}

使用方法:

new Date().format("yyyy-MM-dd hh:mm:ss");

7 一年有多少周

function getTotalWeek(year) {
// 一年第一天是周几
var first = new Date(year,0,1).getDay()
// 计算一年有多少天
if((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0)) {
var allyears = 366
}else {
var allyears = 365
}
// 计算一年有多少周
var week = parseInt((allyears + first) / 7)
if(((allyears + first) % 7) != 0) {
week += 1
}
return week
}

8 当月有多少天

function getCountDays() {
var curDate = new Date();
/* 获取当前月份 */
var curMonth = curDate.getMonth();
/* 生成实际的月份: 由于curMonth会比实际月份小1, 故需加1 */
curDate.setMonth(curMonth + 1);
/* 将日期设置为0, 这里为什么要这样设置, 我不知道原因, 这是从网上学来的 */
curDate.setDate(0);
/* 返回当月的天数 */
return curDate.getDate();
}

持续更新中。。。