Date对象
Date
将1970年一月一日零时至今经过的毫秒数保存。可以精确保存之前之后的285616年的日期。
-
创建一个
Date
对象,要使用new
操作符调用Date
构造函数。let date = new Date(); console.log(date);//Sat May 22 2021 08:33:39 GMT+0800 (中国标准时间)
表示为:2021年5月22日星期六08:33:39 GMT+0800。
要想创建一个指定的时间,就需要传进参数。
let date = new Date(2021,9,1);
console.log(date);//Fri Oct 01 2021 00:00:00 GMT+0800 (中国标准时间)
表示为:10月1日星期五2021 00:00:00 GMT+0800。参进去的参数你也可以写的更明细点。比如把时分秒都参进去,这是可以的。要注意的是,
-
月份是从 0 开始数起的。0-11。0 代表一月,直到 11 代表十二月。
-
小时是0-23。
-
分数是0-59。
-
秒数是从0-59。
-
星期是从0-6。0 代表星期日,6 代表星期六。
-
日期是1-31的。举个例子,你传进的参数是2021,9,0。输出的就不是九月了,是八月的最后一天。假如你传进的天数超过月份的最大天数,也会输出为下个月的第一天。(上面的例子同理,超过上限进一。)
let date = new Date(2021,9,0); console.log(date);//9月30号 let date2 = new Date(2021,9,32); console.log(date2);//11月1号
Date
对象的方法。
方法 | 描述 |
---|---|
getFullYear() | 获取对象的年份,以四个数字返回。 |
setFullYear(year) | 设置日期的年,(例:2021) |
getMonth() | 获取对象的月份,返回0-11。 |
setMonth(month) | 设置日期的月,0-11。 |
getDay() | 获取对象的周数,返回0-6。 |
getDate() | 获取对象的天数,返回1-31。 |
setDate(date) | 设置日期的日,1-31。 |
getHours() | 获取对象的小时,返回0-23。 |
setHours(hours) | 设置日期的时,0-23。 |
getMinutes() | 获取对象的分数,返回0-59。 |
setMinutes(minutes) | 设置日期的分,0-59。 |
getSeconds() | 获取对象的秒数,返回0-59。 |
setSeconds(second) | 设置日期的秒,0-59。 |
getMilliseconds() | 获取对象的毫秒,返回0-999。 |
setMilliseconds(milliseconds) | 设置日期的毫秒,0-999。 |
getTime() | 获取从 1970年1月1号00时00分00秒 到现在的毫秒数。 |
还有UTC日期的方法没有一起列出来。可以去W3c查询。
let date = new Date();
console.log(date.getFullYear());//2021 年
console.log(date.getMonth());//4 月(5月)
console.log(date.getDay());//6 星期
console.log(date.getDate());//22 天
console.log(date.getHours());//14 小时
console.log(date.getMinutes());//29 分钟
console.log(date.getSeconds());//20 秒
console.log(date.getMilliseconds());//164 毫秒
console.log(date.getTime());//1621664960164 1970.1.1 到现在的毫秒数。
当然上面的时间是我编写时的时间。只是做一个实例。上面的代码是获到到现在的时间。
let date = new Date();
console.log(date.getFullYear());//2021
date.setFullYear(2022);
console.log(date.getFullYear());//2022
效果就是如此,修改时间。就不一一举例,都是差不多的代码。
还有几种格式化日期的方法(最后返回的都是字符串)
toDateString()
显示获取到的日期中的周、月、日、年。toTimeString()
显示获取到的日期中的时、分、秒。toLocaleDateString()
显示获取到的日期中的周、月、日、年。toLocaleTimeString()
显示获取到的日期中的时、分、秒。
下面两种和上面的两种表现的格式会不一样。
还有一种是显示UTC日期的方法。
toUTCString()
显示完整的UTC日期。
格式化方法可能会因为每个浏览器上的差异,导致输出的不一致。
Date()
类型重写了toLocaleDateString()
和toString()
和valueOf()
方法。重写后,这几个方法的返回值就变的不一样的了。
let date = new Date();
console.log(date);//Sat May 22 2021 19:13:40 GMT+0800 (中国标准时间)(Object)
console.log(date.toString());//Sat May 22 2021 19:13:40 GMT+0800 (中国标准时间)(String)
console.log(date.toLocaleString());//2021/5/22下午7:13:40(String)
console.log(date.valueOf());//1621682020732(String)
valueOf()
方法不返回字符串,返回的是毫秒数。因此操作符可以使用他的值。
let date1 = new Date(2021,5,1);
let date2 = new Date(2021,5,2);
console.log(date1 > date2);//false
console.log(date1 < date2);//true
日期在前面的会比在后面的要小。因为日期靠前的毫秒数要比靠后的小。
let date1 = new Date();
for(let i=0;i<100;i++){
console.log(i);
}
let date2 = new Date();
console.log("for循环所用时间为:" + (date2-date1) + "毫秒。");for循环所用时间为:3-5毫秒。
获取中间代码的时间差。
纯属瞎编