dayjs 前几秒时间

  •     var secs_befortime = dayjs().subtract(3000000000,'second').format();
    

前言:工作中的经常对时间进行操作处理 ,例如倒计时,距离当前过去了多久等场景,采用原生的时间函数非常不便,本文推荐轻量级的时间处理库 dayjs 进行演示。

一、安装
npm install dayjs

二、引入
import dayjs from 'dayjs'

三、时间获取
// 获取时间戳
dayjs().valueOf() // 1635765368744

// 获取指定时间时间戳
dayjs('2021/10/1 10:10:30').valueOf() // 1633054230000

// 获取年
dayjs().year() // 2021 当前为2021年

// 获取月
dayjs().month() // 10 当前为11月份(因为月份是从0算起,所以要加1)

// 获取当前月份天数
dayjs('2022-11-2').daysInMonth() // 30 11月有30天

// 获取周
dayjs().day() // 当前为星期一 星期(星期日0,星期六6)

// 获取日
dayjs().date() // 1 当前为11月1日

// 获取小时
dayjs().hour() // 19 当前时间19:35

// 获取分钟
dayjs().minute() // 35 当前时间19:35

// 获取秒
dayjs().second() // 56 当前时间19:35:56

// 获取毫秒
dayjs().millisecond() // 588 ( 一秒等于1000毫秒 )

// 增加天数
dayjs().add(16, 'day') // 17 当前时间11月1日

// 减少天数和年份
dayjs().subtract(3, 'day') // 29 当前时间11月1日
dayjs().subtract(3, 'year') // 2018 当前时间2021年

// 格式化
dayjs().format('YYYY') // 2021
dayjs().format('YYYY-MM-DD') // 2021-11-1 当前时间2021-11-1

// 时间之前
dayjs().isBefore('2021-10-1') // false 当前时间是否在2021-10-1 之前

// 时间之后
dayjs().isAfter('2021-10-1') // true 当前时间是否在2021-10-1 之后

// 是否在某一时间段之内 ( 2022-1-1 8:00:00 — 2022-1-9 9:30:00 )
dayjs('2022-1-6 9:00:00').isBetween('2022-1-1 8:00:00', dayjs('2022-1-9 9:30:00')) // true

示例 (是否在某一时间段之内)
dayjs(dayjs().format('YYYY-MM-DD HH:mm:ss')).isBetween(startTime, dayjs(endTime))

以上操作可以满足大部分的时间操作场景。
————————————————
版权声明:本文为CSDN博主「王新焱」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_34402069/article/details/125525767

posted @ 2022-12-28 13:24  盘思动  阅读(257)  评论(0编辑  收藏  举报