dayjs 判断是否今天、本周内、本年内、本年外显示周几、月份等

效果:
在这里插入图片描述

判断是否今天需从 dayjs 中引入 isToday 插件;
判断是否两个日期之间需从 dayjs 中引入 isBetween 插件

import dayjs from 'dayjs'
import isToday from 'dayjs/plugin/isToday'
import isBetween from 'dayjs/plugin/isBetween'

// 注册插件
dayjs.extend(isBetween)
dayjs.extend(isToday)
/**
 * @desc 时间格式转换
 * @params time 时间戳
 * @params local 本地语言环境 中英文
 */
const dayStr = ['日', '一', '二', '三', '四', '五', '六']
// 英文
const dayEnStr = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']

export const handleTime = (time: string, local: string) => {
  // console.log(local);
  // 原始时间格式 -
  // 1711210843626
  const getTime = dayjs(time).format('YYYY-MM-DD-HH-mm-ss')
  const timeArr = getTime.split('-')
  // 本周区间
  const isWeekStar = dayjs().startOf("week")
  const isWeekEnd = dayjs().endOf("week")
  // 本年区间
  const isYearStar = dayjs().startOf("year")
  const isYearEnd = dayjs().endOf("year")

  // 判断是否今天   今天 hh:mm
  if (dayjs(time).isToday()) {
    return local == 'zhCN' ? `今天 ${timeArr[3]}:${timeArr[4]}` : `Today ${timeArr[3]}:${timeArr[4]}`
  }
  // 判断是否本周内  周几 hh:mm
  if (dayjs(time).isBetween(isWeekStar, dayjs(isWeekEnd))) {
    return local == 'zhCN' ? `${dayStr[dayjs(time).day()]} ${timeArr[3]}:${timeArr[4]}` : `${dayEnStr[dayjs(time).day()]} ${timeArr[3]}:${timeArr[4]}`
  }
  // 本周外本年内    xx月xx日
  if (dayjs(time).isBetween(isYearStar, dayjs(isYearEnd))) {
    return local == 'zhCN' ? `${timeArr[1]}${timeArr[2]}` : `${timeArr[1]}month ${timeArr[2]}th`
  }
  // 本年外 xx年xx月xx日
  return local == 'zhCN' ? `${timeArr[0]}${timeArr[1]}${timeArr[2]}` : `${timeArr[1]}month ${timeArr[2]}, ${timeArr[0]}`
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值