重学JavaScript【Date介绍和用法】

74 阅读4分钟

重学JavaScript 篇的目的是回顾基础,方便学习框架和源码的时候可以快速定位知识点,查漏补缺,所有文章都同步在 公众号(道道里的前端栈)github 上。

简介

Date 类型的创建参考了Java早起版本中的 java.util.Date,为此,Date 类型将日期保存为自协调世界时(UTC)时间 1970年1月1日0时 至今所经过的毫秒数,Date 类型可以精确表示 1970年1月1日之前及之后285616年的日期。

使用

Date 类型创建对象是通过 new 操作符来调用 Date 构造函数的:

let now = new Date();
// now: Wed Feb 10 2021 14:53:58 GMT+0800 (中国标准时间)

不传参的情况下,创建的对象将保存当前日期和时间,要创建特定的时间,必须传入其毫秒。

在下面的例子中,now 包括了很多用来解释当前某个时间的方法:

let now = new Date();
now.getDate(); // 返回一个月中的某一天 (1 ~ 31)
now.getDay(); // 返回一周中的某一天 (0 ~ 6)
now.getMonth(); // 返回月份 (0 ~ 11
now.getFullYear(); // 返回当前年份
now.getHours(); // 返回小时 (0 ~ 23)
now.getMinutes(); // 返回分钟 (0 ~ 59)
now.getSeconds(); // 返回秒数 (0 ~ 59)
now.getMilliseconds(); //返回毫秒数 (0 ~ 999);
now.getTime(); // 返回 1970 年 1 月 1 日至今的毫秒数
now.getUTCDate(); // 根据世界时从 now 对象返回月中的一天 (1 ~ 31)
now.getUTCDay(); // 根据世界时从 now 对象返回周中的一天 (0 ~ 6)
now.getUTCMonth(); // 根据世界时从 now 对象返回月份 (0 ~ 11)
now.getUTCFullYear(); // 根据世界时从 now 对象返回四位数的年份
now.getUTCHours(); // 根据世界时返回 now 对象的小时 (0 ~ 23)
now.getUTCMinutes(); // 根据世界时返回 now 对象的分钟 (0 ~ 59)
now.getUTCSeconds(); // 根据世界时返回 now 对象的秒钟 (0 ~ 59)
now.getUTCMilliseconds(); // 根据世界时返回 now 对象的毫秒(0 ~ 999)
now.Parse(); // 返回1970年1月1日午夜到指定日期(字符串)的毫秒数

除了获取一个时间,当然也可以设置一个时间:

now.setDate();	//设置月的某一天 (1 ~ 31)
now.setMonth();	//设置月份 (0 ~ 11)
now.setFullYear();	//设置年份(四位数字)
now.setHours();	//设置小时 (0 ~ 23)
now.setMinutes();	//设置分钟 (0 ~ 59)
now.setSeconds();	//设置秒钟 (0 ~ 59)
now.setMilliseconds();	//设置毫秒 (0 ~ 999)
now.setTime();	//以毫秒设置 now 对象
now.setUTCDate();	//根据世界时设置 now 对象中月份的一天 (1 ~ 31)
now.setUTCMonth();	//根据世界时设置 now 对象中的月份 (0 ~ 11)
now.setUTCFullYear();	//根据世界时设置 now 对象中的年份(四位数字)
now.setUTCHours();	//根据世界时设置 now 对象中的小时 (0 ~ 23)
now.setUTCMinutes();	//根据世界时设置 now 对象中的分钟 (0 ~ 59)
now.setUTCSeconds();	//根据世界时设置 now 对象中的秒钟 (0 ~ 59)
now.setUTCMilliseconds();	//根据世界时设置 now 对象中的毫秒 (0 ~ 999)

为了方便我们用常用的写法来表示日期,Date 类型也提供了一些方法可以直接使用:

now.toDateString(); // 显示日期中的周几、月、日、年
now.toTimeString(); // 显示日其中的时、分。秒和时区
now.toLocaleDateString(); // 人性化的显示日期中的年月日
now.toLocaleTimeString(); //人性化的显示日期中的时分秒

实例

两个日期是可以比较大小的:

let d1 = new Date(2019, 0, 1);
let d2 = new Date(2020, 0, 1);
d1 < d2 // true
d1 > d2 // false

下面我们手动实现一个日历组件,代码已上传至仓库:点击这里,效果图如下:

主要的逻辑有:

  1. 查到某月的天数
  2. 当前周几向前和向后空多少个
  3. 获取当前日期的上个月和下个月
  4. 获取当前日期的上个月末尾日期和下个月末尾日期
  5. 获取当前不包括上个月和下个月的所有日期
  6. 获取上周的周一和周日

以上逻辑放置在仓库的 calendar.js 中,屡清楚这些之后,把它们拼起来再加一点样式即可,细节可查看仓库代码。

我的公众号:道道里的前端栈,每一天一篇前端文章,嚼碎的感觉真奇妙~