前端TS 时间格式化函数

/**
 * 时间日期转换
 * @param date 当前时间,new Date() 格式
 * @param format 需要转换的时间格式字符串
 * @returns 返回拼接后的时间字符串
 */
export function formatDate(date: Date, format: string): string {
  const week: { [key: string]: string } = {
    '0': '日', '1': '一', '2': '二', '3': '三', '4': '四', '5': '五', '6': '六',
  };
  const quarter: { [key: string]: string } = { '1': '一', '2': '二', '3': '三', '4': '四' };

  const we = date.getDay(); // 星期
  const z = getWeek(date); // 周
  const qut = Math.floor((date.getMonth() + 3) / 3).toString(); // 季度

  const opt: { [key: string]: string } = {
    'Y+': date.getFullYear().toString(),
    'm+': (date.getMonth() + 1).toString(),
    'd+': date.getDate().toString(),
    'H+': date.getHours().toString(),
    'M+': date.getMinutes().toString(),
    'S+': date.getSeconds().toString(),
    'q+': quarter[qut], // 季度
  };

  // 处理格式中的特殊标记
  format = format.replace(/(W+)/, (match) => match.length > 1 ? `周${week[we]}` : week[we]);
  format = format.replace(/(Q+)/, (match) => match.length === 4 ? `第${quarter[qut]}季度` : quarter[qut]);
  format = format.replace(/(Z+)/, (match) => match.length === 3 ? `第${z}周` : `${z}`);

  // 替换日期格式中的部分
  Object.keys(opt).forEach((key) => {
    const reg = new RegExp(`(${key})`);
    format = format.replace(reg, (match) => match.length === 1 ? opt[key] : opt[key].padStart(match.length, '0'));
  });

  return format;
}

/**
 * 获取当前日期是第几周
 * @param dateTime 当前传入的日期值
 * @returns 返回第几周数字值
 */
export function getWeek(dateTime: Date): number {
  const temptTime = new Date(dateTime);
  const weekday = temptTime.getDay() || 7;  // 周几 (0-6,0代表星期天)
  
  // 调整日期到上周一
  temptTime.setDate(temptTime.getDate() - weekday + 1);
  const firstDay = new Date(temptTime.getFullYear(), 0, 1);

  // 获取第一周的第一天
  const dayOfWeek = firstDay.getDay();
  const spendDay = dayOfWeek === 0 ? 7 : 7 - dayOfWeek + 1;

  // 计算周数
  const startOfYear = new Date(temptTime.getFullYear(), 0, 1 + spendDay);
  const days = Math.ceil((temptTime.getTime() - startOfYear.getTime()) / 86400000);
  return Math.ceil(days / 7);
}

/**
 * 将时间转换为 `几秒前`、`几分钟前`、`几小时前`、`几天前`
 * @param param 当前时间,new Date() 格式或
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

念九_ysl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值