Date.prototype
在 JS 中,我们一般通过三种形式表示时间,Date 对象、毫秒数、ISO 8601。
new Date() // Thu Aug 18 2022 14:20:47 GMT+0800 (中国标准时间)
Date.now() // 1660803707430
new Date(Date.now() + 8 * 3600 * 1000).toISOString() // '2022-08-18T14:22:31.231Z'
默认情况下,通过new Date()所得到的日期为标准时区。
我们可以通过new Date()来获得当前时间或者给定时间的 Date 对象。
var date = new Date()
var date = new Date(seconds)
Date 对象还有一些方法来获得年份、月份等。
date.getDay() // 一周中第几天
date.getDate() // 一个月中第几天
date.getMouth() // 几月份
date.getFullYear() // 完整年份
我们可以通过Date.now()获得当前时间的毫秒数。
var second = Date.now()
我们也可以给通过Date.parse()获得给定时间的毫秒数。
var seconds = Date.parse('2022-08-18')
ISO 8601
ISO 8601 是一套国际标准的日期和时间表示方法。
根据 ISO 8601,东八区 2004 年 5 月 3 日下午 5 点 30 分 8 秒可以表示为 2004-05-03T17:30:08+08:00。
在 JS 中可以通过toISOString()方法得到 ISO 8601 表示的字符串。
var date = new Date().toISOString()
但toISOString()不会把 Date 对象的时区作为参数,而只会以毫秒数为参数。
这意味着哪怕new Date()的结果是以 +8 区表示,toISOString()的结果仍是以标准时区展示。这就只能在标准时区毫秒数上加上 8 小时的毫秒数。
new Date().toISOString() // 0 区
new Date(Date.now() + 8 * 3600 * 1000).toISOString() // +8区
Day.js
由于 JS 中 Date 的原生 API 实在谈不上好用,更推荐使用Day.js带替代 JS 原生 Date。
安装 Day.js。
npm install dayjs
yarn add dayjs
在项目中引入 Day.js。
import dayjs from 'dayjs';
可以通过dayji()来构造 Dayjs 对象。
var now = dayjs()
var day = dayjs('2022-08-15')
var date = dayjs(new Date())
可以通过isSame()方法比较两个 Dayjs 对象或者毫秒数。
day.isSame(now, 'day')
day.isSame(now, 'Month')
day.isSame('1660805509756', 'day')
可以通过subtract()方法来得到昨天、上个月。
now.subtract(1, 'day') // 昨天
now.subtract(1, 'month') // 上个月
可以通过format()方法格式化日期
day.format('M月DD日') // 8月15日
day.format('YYYY年MM月DD日') // 2022年08月15日