Vue3,TS,格式化时间段

Vue3,TS,格式化时间段

在这个日期格式化方案中,函数会根据两个时间的差异(是否在同一个月、跨月、跨年)输出不同的日期格式。它主要有以下三种格式化规则:

  1. 同一个月内的日期格式

    • 如果起始日期和结束日期在同一个月内,则输出的格式为 23 - 24 SEP 24
    • 例如:"2024-09-23 12:00:00""2024-09-24 18:30:00"
    • 解释:因为都是 2024 年 9 月的日期,所以只显示日期范围,并在后面加上月份和年份。
  2. 跨月的日期格式

    • 如果起始日期和结束日期在同一年但不同的月份,则输出格式为 23 SEP - 25 OCT 24
    • 例如:"2024-09-23 08:00:00""2024-10-25 20:15:00"
    • 解释:在这种情况下,显示起始日期和结束日期的月份,并且由于年份相同,只需要在最后加一次年份。
  3. 跨年的日期格式

    • 如果起始日期和结束日期跨年,则输出格式为 23 SEP 24 - 25 JAN 25
    • 例如:"2024-09-23 14:45:00""2025-01-25 09:00:00"
    • 解释:因为起始日期和结束日期在不同的年份,需要分别在日期后加上年份以避免混淆。
/**
 * Formats a date range into a readable string based on the start and end dates.
 *
 * @param {string} startDateStr - The start date of the range in "YYYY-MM-DD HH:mm:ss" format.
 * @param {string} endDateStr - The end date of the range in "YYYY-MM-DD HH:mm:ss" format.
 * @returns {string} - A formatted string representing the date range.
 *
 * Format examples:
 * - If within the same month: "23 - 24 SEP 24"
 * - If across different months: "23 SEP - 25 OCT 24"
 * - If across different years: "23 SEP 24 - 25 JAN 25"
 */
export const formatDateRange = (startDateStr: string, endDateStr: string): string => {
  const startDate = new Date(startDateStr)
  const endDate = new Date(endDateStr)

  const padZero = (num: number): string =>
    num < 10 ? `0${num}` : num.toString()

  const startDay = padZero(startDate.getDate())
  const startMonth = startDate
    .toLocaleString('en-US', { month: 'short' })
    .toUpperCase()
  const startYear = startDate.getFullYear().toString().slice(-2) // Last two digits of the year

  const endDay = padZero(endDate.getDate())
  const endMonth = endDate
    .toLocaleString('en-US', { month: 'short' })
    .toUpperCase()
  const endYear = endDate.getFullYear().toString().slice(-2) // Last two digits of the year

  // Same year
  if (startYear === endYear) {
    // Same month
    if (startMonth === endMonth) {
      return `${startDay} - ${endDay} ${startMonth} ${startYear}`
    }
    // Different months
    return `${startDay} ${startMonth} - ${endDay} ${endMonth} ${startYear}`
  }

  // Different years
  return `${startDay} ${startMonth} ${startYear} - ${endDay} ${endMonth} ${endYear}`
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值