提升日期处理效率:day.js 实战经验分享

本文介绍了轻量级的日期时间库day.js的使用,包括安装、基础用法、日期格式化、获取与设置日期时间、日期计算以及时间比较等功能。通过实例展示了如何方便地处理JavaScript中的日期和时间。
摘要由CSDN通过智能技术生成

theme: smartblue

本文简介

点赞 + 关注 + 收藏 = 学会了

  1. 本文主要介绍我在工作中使用 day.js 较多的方法。

  2. 本文并不能代替 day.js 官方文档,日常工作中该查文档的还是要查文档。

  3. 本文是写给刚接触 day.js 的工友,让这部分工友能更顺利上手 day.js

  4. 本文不涉及 day.js 插件(王国之泪通关后再写这部分吧)。

day.js 简介

day.js 是一个专门处理日期和时间的工具库,它的体积只有 2KB,非常小。

安装 day.js

npm

安装

npm install dayjs --save

使用

```js // 引入 dayjs import dayjs from 'dayjs'

// 输出当前时间 console.log(dayjs()) ```

cdn

访问 https://www.jsdelivr.com/package/npm/dayjs 下载最新版本的 Day.js。

```html

```

格式化日期格式

前面我们使用 dayjs() 获取到当前的时间,但返回的格式不好看。

01.png

js // 输出当前时间 console.log(dayjs())

day.js 提供了 format() 方法可以格式化时间。《文档:Format》

format() 会返回一个字符串类型的时间。

基础用法

02.png

js // 格式化当前时间 console.log(dayjs().format())

自定义格式

format() 支持自定义日期格式,点击查看支持的格式

常用格式我拷一份放在这里

| 占位符 | 输出 | 详情 | | ------ | ---------------- | --------------- | | YY | 18 | 两位数的年份 | | YYYY | 2018 | 四位数的年份 | | M | 1-12 | 月份,从 1 开始 | | MM | 01-12 | 月份,两位数 | | MMM | Jan-Dec | 缩写的月份名称 | | MMMM | January-December | 完整的月份名称 | | D | 1-31 | 月份里的一天 | | DD | 01-31 | 月份里的一天,两位数 | | d | 0-6 | 一周中的一天,星期天是 0 | | dd | Su-Sa | 最简写的星期几 | | ddd | Sun-Sat | 简写的星期几 | | dddd | Sunday-Saturday | 星期几 | | H | 0-23 | 小时 | | HH | 00-23 | 小时,两位数 | | h | 1-12 | 小时, 12 小时制 | | hh | 01-12 | 小时, 12 小时制, 两位数 | | m | 0-59 | 分钟 | | mm | 00-59 | 分钟,两位数 | | s | 0-59 | 秒 | | ss | 00-59 | 秒 两位数 | | SSS | 000-999 | 毫秒 三位数 | | Z | +05:00 | UTC 的偏移量,±HH:mm | | ZZ | +0500 | UTC 的偏移量,±HHmm | | A | AM PM | | | a | am pm | |

知道这些格式,我们就可以这样写:

```js // 年 dayjs().format('YY') // 返回 23 (写本文时是2023年) dayjs().format('YY') // 返回 2023

// 月 dayjs().format('M') // 返回当前月份(1-12) dayjs().format('MM') // 返回当前月份(01-12),用MM的话,1-9月前面会补0

// 日 dayjs().format('D') // 返回当前月份里的天,比如今天是5月1号,就输出1;如果今天是5月20号,就输出20 dayjs().format('DD') // 返回当前月份里的天,用DD的话,1-9天前面会补0

// 星期 dayjs().format('d') // 返回一周中的一天,星期天是 0

// 小时 dayjs().format('H') // 返回小时 0-23 dayjs().format('HH') // 返回小时 00-23,0-9小时前面会补0 dayjs().format('h') // 返回小时 1-12 dayjs().format('hh') // 返回小时 01-12,1-9小时前面会补0

// 分钟 dayjs().format('m') // 返回分钟 0-59 dayjs().format('mm') // 返回分钟 00-59,0-9分钟前面会补0

// 秒 dayjs().format('s') // 返回秒 0-59 dayjs().format('ss') // 返回秒 00-59,0-9秒前面会补0 dayjs().format('sss') // 返回毫秒数 000-999 ```

需要注意:

  • 大写M表示月份,小写m表示分钟。
  • 大写D表示月份里的一天,小写d表示一周中的一天
  • 大写H是24小时制,小写h是12小时制。比如下午2点 大写H是14,小写h就是2。如果是使用小写h,建议配合A或者a一起使用。

可以将上面的格式组合起来使用

```js /* 目标:输出当前年月日时分秒 规则:年月日用“-”分隔;时分秒用“:“分隔;年月日和时分秒之间用空格分隔 */ dayjs().format('YYYY-MM-DD hh:mm:ss')

/* 目标:输出当前年月日 规则:年月日用“/”分隔 */ dayjs().format('YYYY/MM/DD')

/* 目标:输出当前年月日 规则:使用中文的“年”、“月”、“日”单位 */ dayjs().format('YYYY年MM月DD日') ```

dayjs() 还接受传入时间参数,然后再使用 format() 进行格式化

js dayjs('2023-05-20').format('YYYY年MM月DD日') // 返回 2023年05月20日

简单吧,好用吧~

format() 和其他方法结合起来很好用,后面会举例。

获取/设置日期时间

前面的例子中我们通过 dayjs().format('M') 等方法可以获取当前时间或者指定时间的月份等信息。

day.js 其实也提供了一些方法可以获取或者设置指定日期时间,详情可以看 文档

我这里举个例子。

```js // 获取当前月份。注意:月份从0开始,0表示1月,1表示2月... dayjs().month()

// 设置月份 dayjs().month(10)

// 设置完月份后格式化 dayjs().month(10).format() ```

这个例子用到 month() 方法,如果不传参就会返回当前日期的月份,如果传了参就变成设置月份了。

还有年、日、周、时分秒等其他配置和获取的方法,请参考 文档

日期时间计算

日期计算是工作中常用的功能,比如计算3天后的日期是多少。day.js 提供了很多方便的方法。

增加日期时间

给定一个日期,希望获取该日期的后几天,或者想获取当前时间的半小时后的时间,就可以使用 add() 方法。

add() 方法接收2个参数:

  • 第一个参数是要增加的时间,可以是负值。
  • 第二个参数是时间单位,比如 daymonth 等。

第二个参数支持的单位如下:

| 单位 | 缩写 | 详情 | | ------------- | ---- | -- | | day | d | 日 | | week | w | 周 | | month | M | 月 | | year | y | 年 | | hour | h | 小时 | | minute | m | 分钟 | | second | s | 秒 | | millisecond | ms | 毫秒 |

其实第二个参数还支持 quarter 查询季度,但需要安装 QuarterOfYear 插件。

比如获取当前日期的后10天。

```js dayjs().add(10, 'day')

// 格式化后返回 dayjs().add(10, 'day').format() ```

如果加了10天后夸了月,day.js 会自动判断的。

比如今天是2023年5月24日,加了10天就是2023年6月3日。

获取当前时间的半小时后的时间。

```js dayjs().add(30, 'minute')

// 或者 dayjs().add(0.5, 'hour') ```

如果传入的值是负数,那返回的时间就是往前计算的。

比如获取10天前的时间。

js dayjs().add(-10, 'day')

使用 add() 方法第一个参数最好还是传入正数,因为想获取之前的时间,可以使用 subtract() 方法。

减少日期时间

subtract() 方法和 add() 的用法一样。

subtract() 的作用是返回减去一定时间的值。

比如想获取10天前的时间值可以这样写。

js dayjs().subtract(10, 'day')

subtract() 的第一个参数同样可以传入负数,但没必要这么做。

subtract() 方法很适合用在日历组件的快捷选项,比如获取1周内的时间。

```js // 当前时间 dayjs().format('YYYY-MM-DD hh:mm:ss')

// 7天前的时间 dayjs().subtract(7, 'day').format('YYYY-MM-DD hh:mm:ss') ```

获取开始日期时间

使用 startOf() 方法可以获取开始时间日期。

startOf() 需要传入一个单位参数,这个参数支持以下值:

| 单位 | 缩写 | 详情 | | -------- | --- | ------------------------- | | year | y | 今年一月1日上午 00:00 | | month | M | 本月1日上午 00:00 | | week | w | 本周的第一天上午 00:00 (取决于国际化设置) | | date | D | 当天 00:00 | | day | d | 当天 00:00 | | hour | h | 当前时间,0 分、0 秒、0 毫秒 | | minute | m | 当前时间,0 秒、0 毫秒 | | second | s | 当前时间,0 毫秒 |

其中 quarter 需要另外安装 QuarterOfYear 插件,isoWeek 需要另外安装 IsoWeek 插件。

比如,我要获取当月的1号到今天的日期。

```js // 今天的日期 dayjs().format()

// 本月的第一天日期 dayjs().startOf('month').format() ```

我在项目中,图表部分有时候会有这种需求。

再比如,有些时候我们可能想获取当前时间的本周第一天,比如今天是2023年5月25号星期4,我想看看这周的周一是几号,就可以这么写:

js dayjs().startOf('week').format('DD') // 返回 21。2023年5月21号是星期1

获取结束日期时间

有获取开始日期时间就有获取结束日期时间。

day.js 提供了 endOf() 方法获取结束日期时间。

比如要获取当前日期的 23:59:59

dayjs().endOf('day').format()

endOf() 通常会和 startOf() 结合使用,这样就可以获取一个比较完整的时间段。

比如要获取 2020年2月的开始和结束日期。

// 2020年2月开始日期时间
dayjs('2020-02').startOf('month').format()

// 2020年2月结束日期时间
dayjs('2020-02').endOf('month').format()

像2月这种不能一眼看出有多少天的月份,用 endOf() 方法就非常方便了。

计算2个日期时间差

如果要计算2个日期时间的差异,可以使用 diff() 方法。

diff() 的语法:

```js 时间1.diff(时间2)

时间1.diff(时间2, 时间单位) ```

如果不传第二个参数(时间单位),默认返回毫秒数。

举个例子,计算北京奥运会开幕式到现在过了多少天。

```js // 北京奥运会开幕时间 const openingDate = dayjs('2008-08-08')

// 当前时间 const now = dayjs()

// 计算北京奥运开幕式到现在过了多少毫秒 now.diff(openingDate)

// 计算北京奥运开幕式到现在过了多少天 now.diff(openingDate, 'day') ```

单位时间除了 'day' 之外,还支持以下单位:

| 单位 | 缩写 | 详情 | | ------------- | ---- | ----------------- | | day | d | 日 | | week | w | Week of Year | | quarter | Q | Quarter | | month | M | 月份 (一月 0, 十二月 11) | | year | y | Year | | hour | h | Hour | | minute | m | Minute | | second | s | Second | | millisecond | ms | Millisecond |

日期时间查询

查询指定月份有多少天

我还记得小学数学老师教我们数一个月有多少天的方法。

举起一个拳头👊

03.png

不好意思,搞错了。。。

04.jpg

从食指往小拇指方向数,凸起来的是31天,凹下去的是30天,2月份除外。

因为有闰年的存在,2月的天数是不定的。

day.js 提供了 daysInMonth() 方法可以快速查询指定月份有多少天。

```js dayjs('2008-02').daysInMonth() // 返回29

dayjs('2023-02').daysInMonth() // 返回28 ```

查询时间是否在另一个时间之前

查询一个时间是否在另一个时间之前,用的是 isBefore() 方法。

比如查询当前日期是否在北京奥运会开幕式之前

js dayjs().isBefore(dayjs('2008-08-08'))

isBefore() 接受第二个参数:时间单位。

比如传入 month,就通过年和月来对比。

js ayjs().isBefore(dayjs('2008-08-08'), 'month')

查询时间是否在另一个时间之后

查询一个时间是否在另一个时间之后,用的是 isBefore() 方法。

比如查询当前日期是否在北京奥运会开幕式之后

js dayjs().isAfter(dayjs('2008-08-08'))

isAfter() 也支持传入第二个参数:时间单位。

判断两个时间是否相同

判断两个时间是否相同使用的方法是 isSame()

isSame() 方法默认使用毫秒来判断。

js dayjs().isSame(dayjs('2008-08-08'))

如果想判断年份或者月份是否相同,就需要传入第二个参数:时间单位。

```js // 年份相同就返回 true,否则返回 false dayjs().isSame('2008-08-08', 'year')

// 年份和月份相同才返回 true,否则返回 false dayjs().isSame('2008-08-08', 'month')

// 年月日都相同才返回 true,否则返回 false dayjs().isSame('2008-08-08', 'day') ```

是否在其他两个的日期时间之间

判断一个时间是否在某个时间段内,需要用到 IsBetween 插件。

如果不想下载这个插件,完全可以通过 isBefore()isAfter() 组合起来进行判断。

比如判断当前时间是否在 2019年 至 2025年 之间,可以这么写:

```js // 当前时间 const now = dayjs()

// 判断结果 now.isAfter('2019') && now.isBefore('2025') ```

推荐阅读

👍《眨个眼就学会了Pixi.js》

👍《P5.js 光速入门》

👍《Fabric.js从入门到膨胀》

👍《前端新宠 Svelte 带来哪些新思想?赶紧学起来!》

👍《物理世界的互动之旅:Matter.js入门指南》

点赞 + 关注 + 收藏 = 学会了

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
swiperChange(e) { if (this.data.backChange) { this.setData({ backChange: false, }); return; } //计算第三个索引 let rest = 3 - e.detail.current - this.data.oldCurrent; let dif = e.detail.current - this.data.oldCurrent; let date; if (dif === -2 || (dif > 0 && dif !== 2)) { //向右划的情况,日期增加 if (this.data.open) { date = new Date(this.data.selectDay.year, this.data.selectDay.month); this.setMonth(date.getFullYear(), date.getMonth() + 1, undefined); this.getIndexList({ setYear: this.data.selectDay.year, setMonth: this.data.selectDay.month, dateIndex: rest, }); } else { date = new Date( this.data.selectDay.year, this.data.selectDay.month - 1, this.data.selectDay.day + 7 ); this.setMonth( date.getFullYear(), date.getMonth() + 1, date.getDate() ); this.getIndexList({ setYear: this.data.selectDay.year, setMonth: this.data.selectDay.month - 1, setDay: this.data.selectDay.day + 7, dateIndex: rest, }); } } else { //向左划的情况,日期减少 if (this.data.open) { date = new Date( this.data.selectDay.year, this.data.selectDay.month - 2 ); this.setMonth(date.getFullYear(), date.getMonth() + 1, undefined); this.getIndexList({ setYear: this.data.selectDay.year, setMonth: this.data.selectDay.month - 2, dateIndex: rest, }); } else { date = new Date( this.data.selectDay.year, this.data.selectDay.month - 1, this.data.selectDay.day - 7 ); this.setMonth( date.getFullYear(), date.getMonth() + 1, date.getDate() ); this.getIndexList({ setYear: this.data.selectDay.year, setMonth: this.data.selectDay.month - 1, setDay: this.data.selectDay.day - 7, dateIndex: rest, }); } } this.setData({ oldCurrent: e.detail.current, }); this.setSwiperHeight(e.detail.current); },
06-12

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值