All files / src/utils date.ts

100% Statements 16/16
93.33% Branches 14/15
100% Functions 4/4
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37        4x 4x 4x 4x         5x 5x               16x 16x 6x 5x               11x 8x 8x    
import dayjs from 'dayjs'
 
// 香港课税年度:4/1–3/31
export function taxYearOf(date: Date): string {
  const y = date.getFullYear()
  const m = date.getMonth() + 1
  const startYear = m >= 4 ? y : y - 1
  return `${startYear}-${startYear + 1}`
}
 
/** 解析失败返回空串,避免 'Invalid Date' 直接渲染上屏 */
export function formatDate(date: string | Date | null | undefined, template = 'YYYY-MM-DD'): string {
  const d = dayjs(date)
  return d.isValid() ? d.format(template) : ''
}
 
/**
 * 后端月结单 month 为 yyyyMM(如 '202603')→ 'yyyy-MM'。
 * 已格式化的 'yyyy-MM' 原样返回;空值/非法值返回空串(原来会把 null 拼成 'null')。
 */
export function formatYearMonth(month: string | null | undefined): string {
  const raw = String(month ?? '').trim()
  if (/^\d{6}$/.test(raw)) return `${raw.slice(0, 4)}-${raw.slice(4, 6)}`
  if (/^\d{4}-\d{2}$/.test(raw)) return raw
  return ''
}
 
/**
 * 日期串 → 'yyyy-MM'。直接用 slice(0,7) 会在后端下发非补零日期时切出脏值
 * ('2026-3-5'.slice(0,7) === '2026-3-'),故交给 dayjs 解析后再格式化。
 */
export function toYearMonth(date: string | Date | null | undefined): string {
  if (!date) return ''
  const d = dayjs(date)
  return d.isValid() ? d.format('YYYY-MM') : ''
}