dayjs 常用方法
前言:工作中的經常對時間進行操作處理 ,例如倒計時,距離當前過去了多久等場景,采用原生的時間函數非常不便,本文推薦輕量級的時間處理庫 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))
以上操作可以滿足大部分的時間操作場景。
總結
以上是生活随笔為你收集整理的dayjs 常用方法的全部內容,希望文章能夠幫你解決所遇到的問題。