Vue3,TS,格式化时间段
在这个日期格式化方案中,函数会根据两个时间的差异(是否在同一个月、跨月、跨年)输出不同的日期格式。它主要有以下三种格式化规则:
同一个月内的日期格式:
- 如果起始日期和结束日期在同一个月内,则输出的格式为
23 - 24 SEP 24
。- 例如:
"2024-09-23 12:00:00"
到"2024-09-24 18:30:00"
。- 解释:因为都是 2024 年 9 月的日期,所以只显示日期范围,并在后面加上月份和年份。
跨月的日期格式:
- 如果起始日期和结束日期在同一年但不同的月份,则输出格式为
23 SEP - 25 OCT 24
。- 例如:
"2024-09-23 08:00:00"
到"2024-10-25 20:15:00"
。- 解释:在这种情况下,显示起始日期和结束日期的月份,并且由于年份相同,只需要在最后加一次年份。
跨年的日期格式:
- 如果起始日期和结束日期跨年,则输出格式为
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}`
}