关于时间的处理 | 程序员必备小知识

3,847 阅读4分钟

掘金年度人气作者

本文用实际业务场景来介绍 Day.js 的使用,后续将会不断补充,也欢迎掘友在评论中留下你的实际业务场景,这里将给出答案

Day.js是一个极简的JavaScript库,可以为现代浏览器解析、验证、操作和显示日期和时间。而且其大小只有2KB,比 Moment.js 轻便很多。

在Vue、React中先执行npm install dayjs --save安装day.js。通过import dayjs from 'dayjs'引入使用。

解析毫秒级时间戳并格式化

格式化格式:2021-9-24 21:39:23

dayjs(1632490763000).format('YYYY-MM-DD HH:mm:ss')

解析秒级时间戳并格式化

格式化格式:2021-9-24 21:39:23

dayjs.unix(1632490763).format('YYYY-MM-DD HH:mm:ss')

获取当天00:00:00和23:59:59的时间戳

  • 当天00:00:00
dayjs().startOf('date').valueOf()//毫秒级时间戳
dayjs().startOf('date').unix()//秒级时间戳
  • 当天23:59:59
dayjs().endOf('date').valueOf()//毫秒级时间戳
dayjs().endOf('date').unix()//秒级时间戳

获取明天的时间戳

dayjs().add(1, 'day').valueOf()//毫秒级时间戳
dayjs().add(1, 'day').unix()//秒级时间戳

获取昨天的时间戳

dayjs().add(-1, 'day').valueOf()//毫秒级时间戳
dayjs().add(-1, 'day').unix()//秒级时间戳

获取当前时间7天前00:00:00和7天后23:59:59的毫秒级时间戳

  • 当前时间7天前00:00:00的毫秒级时间戳
dayjs().subtract(7, 'day').startOf('date').valueOf()
  • 当前时间7天后23:59:59的毫秒级时间戳
dayjs().add(7, 'day').endOf('date').valueOf()

获取当前时间所在月份第一天00:00:00和最后一天23:59:59的秒级时间戳

  • 当前时间所在月份第一天00:00:00的秒级时间戳
dayjs().startOf('month').unix()
  • 当前时间所在月份最后一天23:59:59的秒级时间戳
dayjs().endOf('month').unix()

获取上个月24号00:00:00和下个月24号23:59:59的秒级时间戳

  • 上个月24号00:00:00的秒级时间戳
dayjs().subtract(1, 'month').date(24).startOf('date').unix()
  • 下个月24号23:59:59的秒级时间戳
dayjs().subtract(1, 'month').date(24).endOf('date').unix()

获取上周一00:00:00和下周一23:59:59的毫秒级时间戳

  • 上周一00:00:00的毫秒级时间戳
dayjs().subtract(1, 'week').day(1).startOf('date').valueOf()
  • 下周一23:59:59的毫秒级时间戳
dayjs().add(1, 'week').day(1).endOf('date').valueOf()

获取去年12月24号00:00:00和明年12月24号00:00:00的秒级时间戳

  • 去年12月24号00:00:00的秒级时间戳
dayjs().subtract(1, 'year').month(11).date(24).startOf('date').unix()
  • 明年12月24号00:00:00的秒级时间戳
dayjs().add(1, 'year').month(11).date(24).startOf('date').unix()

判断当前时间是在2021年9月25日之前还是之后,还是就是此刻

const time = dayjs('2021-09-25');
if(dayjs().isBefore(time,'date')){
    //在2021年9月25日之前
}else if(dayjs().isAfter(time,'date')){
    //在2021年9月25日之后
}else if(dayjs().isSame(time,'date')){
    //就在2021年9月25日今天
}

判断当前时间是不是在2021年9月20日和2021年9月25日之间

const time1 = dayjs('2021-09-20');
const time2 = dayjs('2021-09-25');
if(dayjs().isAfter(time2,'date') && dayjs().isBefore(time2,'date')){
  //在2021年9月20日和2021年9月25日之间
}

或者引入Day.js的isBetween插件来实现

import dayjs from 'dayjs';
import isBetween from 'dayjs/plugin/isBetween';
dayjs.extend(isBetween);
const time1 = dayjs('2021-09-20');
const time2 = dayjs('2021-09-25');
if( dayjs().isBetween(time1, time2, 'date') ){
  //在2021年9月20日和2021年9月25日之间
}

格式化一个秒级时间戳为xxxx年xx月xx日是小明的生日

dayjs.unix(1632490763).format('YYYY-MM-DD HH:mm:ss是小明的生日')

后续

欢迎掘友在评论中留下你的实际业务场景,这里将给出答案