actualDeliveryDate.helpers.js 1.26 KB
const CHINA_TIME_OFFSET_MS = 8 * 60 * 60 * 1000
const MILLISECOND_TIMESTAMP_PATTERN = /^\d{13}$/

function padDatePart(value) {
  return String(value).padStart(2, '0')
}

function isValidYmd(year, month, day) {
  const date = new Date(Date.UTC(year, month - 1, day))
  return (
    date.getUTCFullYear() === year &&
    date.getUTCMonth() === month - 1 &&
    date.getUTCDate() === day
  )
}

function formatChinaDateFromTimestamp(timestamp) {
  const chinaDate = new Date(timestamp + CHINA_TIME_OFFSET_MS)
  if (!Number.isFinite(chinaDate.getTime())) return ''
  return `${chinaDate.getUTCFullYear()}-${padDatePart(
    chinaDate.getUTCMonth() + 1
  )}-${padDatePart(chinaDate.getUTCDate())}`
}

export function formatActualDeliveryDateForDisplay(value) {
  if (value === undefined || value === null || value === '') return ''
  const text = String(value).trim()
  const dateMatch = text.match(/^(\d{4})-(\d{2})-(\d{2})/)
  if (dateMatch) {
    const [, year, month, day] = dateMatch.map(Number)
    return isValidYmd(year, month, day)
      ? `${dateMatch[1]}-${dateMatch[2]}-${dateMatch[3]}`
      : ''
  }
  if (!MILLISECOND_TIMESTAMP_PATTERN.test(text)) return ''
  const timestamp = Number(text)
  return Number.isFinite(timestamp)
    ? formatChinaDateFromTimestamp(timestamp)
    : ''
}