JavaScript基本引用类型之Date

31 阅读4分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第13天,点击查看活动详情

前言

ECMAScript的Date类型参考了Java早期版本中的java.util.Date,所以Date类型将日期保存为1970年1月1日零时到现在所经过的毫秒数。使用这种计时方式,可以表示的时间范围是从1970年1月1日零时到之后的285616年。

创建日期对象

我们使用关键字new来调用Date构造函数,这个函数可以接收参数,也可以不接收参数,当不传参数时返回当前时间,当我们要基于某一个具体时间构造时间对象时,需要传递自1970年1月1日零时起的毫秒数,传递的参数不是毫秒数时会默认调用Date.parse()或Date.UTC()。

const time = new Date()
console.log(time)  // Thu Oct 13 2022 22:10:37 GMT+0800 (中国标准时间)

1.Date.parse
Date.parse()支持的时间格式为: "月/日/年"、 "月名 日,年"、 "周几 月名 日 年 时 :时:分:秒 时区"、ISO 8601扩展格式即YYYY-MM-DDTHH:mm:ss:sssZ

console.log(new Date(Date.parse('1/12/2022')))  //Wed Jan 12 2022 00:00:00 GMT+0800 (中国标准时间)

console.log(new Date('July 12,2022')) // 默认会使用Date.parse格式化 Tue Jul 12 2022 00:00:00 GMT+0800 (中国标准时间)
console.log(new Date('May 23 14:14:14 GMT-0700')) // Thu May 24 2001 05:14:14 GMT+0800 (中国标准时间)
console.log(new Date('2022-12-23T14:00:00'))  // Fri Dec 23 2022 14:00:00 GMT+0800 (中国标准时间)

如果传入字符串不能表示日期会返回NaN,而对于越界的日期不同的浏览器会有不同的处理方法,据说Opera浏览器会返回当前时间,我没有Opera浏览器,无法验证。

console.log(new Date(111/222)) // NaN
console.log(new Date('2/30/2022')) // 谷歌浏览器当成3月2号处理了 Wed Mar 02 2022 00:00:00 GMT+0800 (中国标准时间)

2.Date.UTC
Date.UTC()函数参数为可选参数,年、月、日、时、分、秒、毫秒,其中年和月是必传,其他参数根据需要传入,需要注意的是月份的合法直是0-11,0表示1月,11表示12月

console.log(new Date(Date.UTC(2022,9))) // Sat Oct 01 2022 08:00:00 GMT+0800 (中国标准时间)
console.log(new Date(2022,10,1)) // 同样也可以默认使用UTC格式化 Tue Nov 01 2022 00:00:00 GMT+0800 (中国标准时间)

日期格式化方法

toDateString()、toTimeString()、toLocaleDateString()、toLocaleTimeString()、toUTCString()都是专门用于格式化日期的方法,可以根据自己的需要选择不同的格式化方法和组合,虽然现在momentjsdayjs用起来比较方便,但是多掌握点原理毕竟是不错的。

// toDateStirng() 返回周几 月 日 年 
console.log(new Date().toDateString()) //Thu Oct 13 2022
// toTimeString() 返回时分秒时区
console.log(new Date().toTimeString()) // 22:42:35 GMT+0800 (中国标准时间)
// toLocalDateString() 返回年月日
console.log(new Date().toLocaleDateString()) //2022/10/13
// toLocaleTimeString() 返回时分秒
console.log(new Date().toLocaleTimeString()) //22:46:14
// toUTCString() 返回UTC格式
console.log(new Date().toUTCString()) //Thu, 13 Oct 2022 14:48:15 GMT

其他方法

参见下表

image.png 下面挑两个常用的来讲一下,其他需要用到的时候查表即可

1.getMonth() 返回值为0-11 表示112月
console.log(new Date('2022/10/13').getMonth()) // 9
2.setMonth() 直接修改日期月份 0-11 如果值大于11 直接加年
let now = new Date('2022/10/13')
now.setMonth(4) 
console.log(now.toLocaleDateString())  // 2022/5/13

let now = new Date('2022/10/13')
now.setMonth(4) 
now.setMonth(16)
console.log(now.toLocaleDateString()) //2023/5/13

let now = new Date('2022/10/13')
now.setMonth(4) 
now.setMonth(28)
console.log(now.toLocaleDateString()) // 2024/5/13

以上就是今天Date对象的全部内容,欢迎点赞支持。