var date = new Date()
console.log(date.getFullYear())
console.log(date.getYear()) // 现在已经不用了,获取的是1900到当前年份的差值
console.log(date.getMonth()) // 月份是 0~11
console.log(date.getDate()) // 得到日期的号数
console.log(date.getHours())
console.log(date.getMinutes())
console.log(date.getSeconds())
console.log(date.getDay()) // 获取星期几 0~6,星期天就是0
console.log(date.getMilliseconds()) // 获取当前日期的毫秒(一般用不到)1秒===1000毫秒
还有一系列设置API,可以把日期拨到某个时间点
date.setFullYear(2021) // 把date日期对象设置为2021年
date.setMonth(5) // 把日期拨到6月
date.setDate(20) // 把日期设置成20号
// date.setDay() // 这个方法是不存在的,星期几是根据日期自动计算的,不能手动设置
date.setHours(7)
date.setMinutes(7)
date.setSeconds(7)
// date.setTime(0) // 设置时间戳,date就会根据时间戳来计算,设置为0那么date九变成了1970-1-1,这个方法一般用的不多
set API的特点
var date = new Date()
// set系列的API如果参数超过正常返回,日期会自动取往前或者往后推算
date.setMonth(12)
date.setDate(0) // 会把时间设置为上个月的最后一天,可以用来找
一个月一共多少天
console.log(date)
// set系列API可以设置更精细的范围
var date1 = new Date()
// date1.setFullYear(2008, 2, 1) // 日期拨到2008年3月1号,但是不能设置时分秒
date1.setMonth(2, 1) // 可以同时设置月和日
date1.setHours(3, 3, 3)
console.log(date1)
日期的to string
var date = new Date()
console.log(date)
console.log(date.toString())
console.log(date.toDateString()) // 转换为日期字符串
console.log(date.toLocaleDateString()) // 转换为本地日期字符串
console.log(date.toTimeString()) // 转换为时间字符串
console.log(date.toLocaleTimeString()) // 转换为本地时间字符串
console.log(date.toLocaleString()) // 转换为本地日期加时间完整的字符串
console.log(date.toUTCString()) // 转换为标准时区的日期和时间
**
案例:日历-上下月
**
document.getElementById(‘next’).onclick = function () {
n++;
calendar();
}
document.getElementById(‘prev’).onclick = function () {
n–;
calendar();
}
function calendar () {
// 获取当前日期
var date = new Date();
// 根据n的值获取当前月份的日期对象
date.setMonth(date.getMonth() + n);
// 获取年和月设置title
var title = date.getFullYear() + '年' + (date.getMonth() + 1) + '月';
document.getElementById('title').innerHTML = title;
// 获取今天是几号
var today = date.getDate();
// 把日期拨到这个月1号
date.setDate(1);
// 获取1号是星期几
var week = date.getDay();
// 把日期拨到下个月0号,也就是这个月的最后一天
date.setMonth(date.getMonth() + 1, 0);
// 获取最后一天是几号,那么这个月就总共有这么多天
var totalDay = date.getDate();
var str = '';
// 根据星期几插入空的li
for (var i = 0; i < week; i++) {
str += '<li></li>';
}
// 根据总天数插入有值的li
for (var j = 1; j <= totalDay; j++) {
if (n < 0) {
// 以前的日期全部置灰
str += '<li class="ccc">' + j + '</li>';
} else if (n === 0) {
// 当前月份都要判断
if (j < today) {
str += '<li class="ccc">' + j + '</li>';
} else if (j === today) {
str += '<li class="red">' + j + '</li>';
} else if ((week + j) % 7 === 0 || (week + j) % 7 === 1) {
// 每个月1号星期几不确定,但是让空白li数量在加上号数,这个值就固定了
str += '<li class="sun">' + j + '</li>';
} else {
str += '<li>' + j + '</li>';
}
} else {
// 以后的日期只需要判断周末
if ((week + j) % 7 === 0 || (week + j) % 7 === 1) {
// 每个月1号星期几不确定,但是让空白li数量在加上号数,这个值就固定了
str += '<li class="sun">' + j + '</li>';
} else {
str += '<li>' + j + '</li>';
}
}
}
// 把str作为html字符串放进ul里
ul.innerHTML = str;
}