dateFormate.js 2.28 KB
import dayjs from 'dayjs'

export function formattedTime(rawTime) {
  try {
    // 格式校验
    if (!/^\d{12}$/.test(rawTime)) {
      this.$message.error('无效的时间格式 (需要12位数字)')
    }

    // 拆分时间组件
    const components = {
      year: parseInt(rawTime.slice(0, 2)),
      month: parseInt(rawTime.slice(2, 4)),
      day: parseInt(rawTime.slice(4, 6)),
      hour: parseInt(rawTime.slice(6, 8)),
      minute: parseInt(rawTime.slice(8, 10)),
      second: parseInt(rawTime.slice(10, 12))
    }

    // 验证有效性
    if (
      components.month < 1 || components.month > 12 ||
      components.day < 1 || components.day > 31 ||
      components.hour > 23 ||
      components.minute > 59 ||
      components.second > 59
    ) {
      this.$message.error('时间参数超出有效范围')
    }

    // 转换为完整年份 (假设是20世纪和21世纪)
    const fullYear = components.year < 50 ?
      2000 + components.year :
      1900 + components.year

    // 使用 dayjs 构建日期对象
    const date = dayjs()
      .year(fullYear)
      .month(components.month - 1) // 月份从0开始
      .date(components.day)
      .hour(components.hour)
      .minute(components.minute)
      .second(components.second)

    // 验证日期是否有效
    if (!date.isValid()) {
      this.$message.error('生成的时间无效')
    }
    // 返回格式化结果
    return date.format('YYYY-MM-DD HH:mm:ss')
  } catch (err) {
    console.error('时间转换错误:', err)
    this.$message.error('时间转换失败')
  }
}


export function convertTimeFormat(rawTime, inputFormat, outputFormat) {
  try {
    // 特殊处理时间戳
    if (inputFormat === 'X' || inputFormat === 'x') {
      const timestamp = inputFormat === 'X' ?
        parseInt(rawTime) * 1000 : parseInt(rawTime);
      return dayjs(timestamp).format(outputFormat);
    }

    // 使用 Day.js 解析输入时间
    const dateObj = dayjs(rawTime, inputFormat);

    // 验证解析结果
    if (!dateObj.isValid()) {
      console.log('输入时间无效')
      return '转换失败: 无法解析输入时间'
    }
    // 转换为目标格式
    return dateObj.format(outputFormat);
  } catch (error) {
    console.error('时间转换错误:', error);
    return `转换失败: ${error.message}`;
  }
}