持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第1天,点击查看活动详情
Date 日期对象
基本功能
-
功能:Date 对象用于处理日期与时间,返回一个日期对象
-
创建:不同于 Number、String等对象,创建一个新Date对象的唯一方法是通过 new 操作符
语法格式
当 Date 作为构造函数调用并传入多个参数时,如果数值大于合理范围时(如月份为 13 或者分钟数为 70),相邻的数值会被调整。比如 new Date(2013, 13, 1) 等于 new Date(2014, 1, 1),它们都表示日期 2014-02-01(注意月份是从 0 开始的)。其他数值也是类似,new Date(2013, 2, 1, 0, 70) 等于 new Date(2013, 2, 1, 1, 10),都表示同一个时间:2013-03-01T01:10:00
。
// new Date();
// new Date(value);
// new Date(dateString);
// new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
new Date();
当前日期和时间
var curDate = new Date();
console.log(curDate); //Tue Oct 18 2022 11:14:07 GMT+0800 (中国标准时间)
new Date(value);
一个 Unix 时间戳(Unix Time Stamp),它是一个整数值,表示自 1970 年 1 月 1 日 00:00:00 UTC(the Unix epoch)以来的毫秒数,忽略了闰秒。请注意大多数 Unix 时间戳功能仅精确到最接近的秒。
var stampDate = new Date(1251254534516)
console.log(stampDate); //Wed Aug 26 2009 10:42:14 GMT+0800 (中国标准时间)
new Date(dateString);
表示日期的字符串值。该字符串应该能被Date.parse()
方法识别
var strDate = new Date("2022-11-11 00:00:00");
console.log(strDate); //Fri Nov 11 2022 00:00:00 GMT+0800 (中国标准时间)
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
`year` - 表示年份的整数值。0 到 99 会被映射至 1900 年至 1999 年,其它值代表实际年份。
`monthIndex` - 表示月份的整数值,从 0(1 月)到 11(12 月)。
`date` - 可选,表示一个月中的第几天的整数值,从 1 开始。默认值为 1。
`hours` - 可选,表示一天中的小时数的整数值 (24 小时制)。默认值为 0(午夜)。
`minutes` - 可选,表示一个完整时间(如 01:10:00)中的分钟部分的整数值。默认值为 0。
`seconds` - 可选,表示一个完整时间(如 01:10:00)中的秒部分的整数值。默认值为 0。
`milliseconds` - 可选,表示一个完整时间的毫秒部分的整数值。默认值为 0。
不加 new 关键字
- 若将它作为常规函数调用(即不加 new 操作符),将返回一个字符串,而非
Date
对象,而字符串不能参与时间日期的计算
//new 创建Date对象,返回的是对象格式,可以参与时间计算
var curDate = new Date();
var sepDate = new Date("2020-11-11 00:00:00");
console.log(curDate); //Tue Oct 18 2022 10:49:29 GMT+0800 (中国标准时间)
console.log(typeof curDate); //object
console.log(curDate - sepDate); //61037391300 - 计算时间差,返回的是间隔毫秒数
//不通过new创建,直接使用Date对象,返回的是字符串格式,且不能指定时间
var dirDate = Date();
var dirSepDate = Date("2020-11-11 00:00:00");
console.log(dirDate); //Tue Oct 18 2022 10:50:02 GMT+0800 (中国标准时间)
console.log(dirSepDate); //Tue Oct 18 2022 10:50:02 GMT+0800 (中国标准时间)
console.log(typeof dirDate); //string
常用方法
获取/设置 年月日 周
-
年:
getFullYear()
setFullYear()
-
月:
getMonth()
setMonth()
-
日:
getDate()
setDate()
-
周:
getDay()
setDay()
获取/设置 时分秒 毫秒
-
时:
getHours()
setHours()
-
分:
getMinutes()
setMinutes()
-
秒:
getSeconds()
setSeconds()
-
毫秒:
getMilliseconds()
setMilliseconds()
/**常用方法
* ----获取[返回number格式]----
* 年 - getFullYear()
* 月 - getMonth() --> 0[Jan]-11[Dec]
* 日 - getDate()
* 周 - getDay() --> 0[Sunday] 1-6[Monday-Saturday]
* 时 - getHours()
* 分 - getMinutes()
* 秒 - getSeconds()
* 毫秒 - getMilliseconds()
* 毫秒 - getTime() --> 距离1970-1-1 00:00:00
* ----设置[返回毫秒,修改date]----
* 将上述get改为set即可
*/
var curDate = new Date();
console.log(curDate) //Tue Oct 18 2022 12:16:25 GMT+0800 (中国标准时间)
console.log(curDate.getFullYear()) //2022
console.log(curDate.getMonth()+1-0) //10 --> Oct
console.log(curDate.getDate()) //18
console.log(curDate.getDay()) //2
console.log(curDate.getHours()) //12
console.log(curDate.getMinutes()) //16
console.log(curDate.getSeconds()) //25
console.log(curDate.getMilliseconds()) //699
console.log(curDate.getTime()) //1666066585699
console.log(curDate.setFullYear(2000)) //971842585699
console.log(curDate) //Wed Oct 18 2000 12:16:25 GMT+0800 (中国标准时间)
示例
模拟倒计时功能一
var countIntervalID;
var regularTime = /[0-9]{4}(-[0-9]{2}){2}\x20[0-9]{2}(:[0-9]{2}){2}/;
function countDown(targetTime){
var diffTime;
var curTime = new Date();
var timeDetailObj = {
date:null,
hours:null,
minutes:null,
seconds:null
}
if (targetTime <= curTime) {
document.getElementById("display").innerHTML = `Time has already gong.Today is ${curTime.getFullYear()}/${curTime.getMonth()+1}/${curTime.getDate()}`;
stopCount(countIntervalID)
} else {
diffTime = targetTime - curTime; //返回的毫秒数
timeDetailObj.date = parseInt(diffTime/(1000*60*60*24));
timeDetailObj.hours = parseInt(diffTime/1000%(60*60*24)/(60*60));
timeDetailObj.minutes = parseInt(diffTime/1000%(60*60)/60);
timeDetailObj.seconds = parseInt(diffTime/1000%60);
console.log(timeDetailObj)
document.getElementById("display").innerHTML = `距离结束 ${timeDetailObj.date} 天 ${timeDetailObj.hours} 时 ${timeDetailObj.minutes} 分 ${timeDetailObj.seconds} 秒`
}
return timeDetailObj;
}
function countTime(){
var inputTime = document.getElementById("text").value;
document.getElementById("display").innerHTML = "" //重新计时清空之前的显示
if (regularTime.test(inputTime)) {
var targetTime = new Date(inputTime)
if (!countIntervalID) {
countIntervalID = setInterval(countDown,1000,targetTime);
} //else none to do
} else {
alert("输入格式要求:yyyy-mm-dd hh:mm:ss");
}
}
function stopCount(){
clearInterval(countIntervalID);
countIntervalID = null;
}
document.getElementById("start").addEventListener("click",countTime)
document.getElementById("stop").addEventListener("click",stopCount)
模拟倒计时功能二
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div></div>
<button>开始计时</button>
</body>
<script>
/* 功能:距离双十一的倒计时(几天、几时、几分、几秒 -->时间拼0,间隔用冒号并闪烁),时间到,提示单身快乐 */
let display = document.getElementsByTagName("div")[0];
let btn = document.getElementsByTagName("button")[0];
let ultimateTime = new Date("2022-11-11 00:00:00");
let nowTime;
let differTime;
let days;
let hours;
let minutes;
let seconds;
//计算出具体时间:天、时、分、秒
function timeCount(){
nowTime = new Date();
differTime = ultimateTime - nowTime; //Date对象相减,返回毫秒差
days = Math.floor(differTime / (1000 * 3600 * 24));
hours = Math.floor(differTime / (1000 * 3600) % 24);
minutes = Math.floor(differTime / (1000 * 60) % 60);
seconds = Math.floor(differTime / 1000 % 60);
}
//点击计时
btn.addEventListener("click",function(){
let colon = true; //约定:true 冒号显示,false 冒号不显示
let countInterval = setInterval(() => {
timeCount();
let strDay = `<b>距离双十一:</b><b>${Number(days) === 0?"最后时刻":days+" 天 "}</b>`;
let strHour = `<b>${Number(hours) < 10?"0"+hours:hours}</b>`;
let strMinute = `<b>${Number(minutes) < 10?"0"+minutes:minutes}</b>`;
let strSecond = `<b>${Number(seconds) < 10?"0"+seconds:seconds}</b>`;
let strColon = `<b style="display:inline-block;width:16px;text-align:center;">:</b>`;
let strSpace = `<b style="display:inline-block;width:16px;text-align:center;"> </b>`;
// if(colon){ //带冒号
// display.innerHTML = `${strDay}${strHour}${strColon}${strMinute}${strColon}${strSecond}`;
// colon = false;
// } else { //不带冒号
// display.innerHTML = `${strDay}${strHour}${strSpace}${strMinute}${strSpace}${strSecond}`;
// colon = true;
// }
/*上述代码优化 version 0.1:*/
// let strGap; //作为中间连接,是冒号还是空格
// if (colon) {
// strGap = strColon;
// colon = false;
// } else {
// strGap = strSpace;
// colon = true;
// }
// display.innerHTML = `${strDay}${strHour}${strGap}${strMinute}${strGap}${strSecond}`;
/*上述代码优化 version 0.2:判断秒为奇数还是偶数,此时就可以不用中间变量判断了*/
let strGap;
Number(seconds)%2 == 0 ? strGap = strColon : strGap = strSpace;
display.innerHTML = `${strDay}${strHour}${strGap}${strMinute}${strGap}${strSecond}`;
//计时结束,显示结果
if(differTime <= 0) {
display.innerHTML = "单身快乐";
clearInterval(countInterval); //清除计时器
}
}, 1000);
});
</script>
</html>