前端常用的时间格式处理

import {
    fillZero } from '@/utils/utils'
export const shortcuts = [
  ['最近一周', 7],
  ['最近一个月', 30],
  ['最近三个月', 90],
  ['最近半年', 180],
  ['最近一年', 365]
]

/**
 * dateParams 获取时间对象
* @param   {Number}   value   时间戳
 */
export const dateParams = (value) => {
   
  const dateObj = value ? new Date(value) : new Date()
  const time = dateObj.getTime()
  const year = dateObj.getFullYear()
  const month = dateObj.getMonth()
  const date = dateObj.getDate()
  const day = dateObj.getDay()
  return {
   
    dateObj,
    year,
    month,
    date,
    day,
    time
  }
}

/**
 * dateStartAndLast
 * @param  {String}   value    时间
 */
export const dateStartAndLast = (value) => {
   
  const startDate = value ? new Date(value) : new Date()
  startDate.setDate(1) // 第一天

  const endDate = new Date(startDate)
  endDate.setMonth(startDate.getMonth() + 1)
  endDate.setDate(0) // 最后一天

  return {
   
    // start
    startDate: startDate.getDate(),
    startDay: startDate.getDay(),
    startMonth: startDate.getMonth(),
    startYear: startDate.getFullYear(),
    // end
    endDate: endDate.getDate(),
    endDay: endDate.getDay(),
    endMonth: endDate.getMonth(),
    endYear: endDate.getFullYear()
  }
}

export const dateFormatter = (date) => {
   
  const dateObj = new Date(date)
  const year = `${
     dateObj.getFullYear()}`.padStart(4, '0')
  const month = `${
     dateObj.getMonth() + 1}`.padStart(2, '0')
  const day = `${
     dateObj.getDate()}`.padStart(2, '0')
  return `${
     year}-${
     month}-${
     day}`
}

/**
 * dateRangeGen  近周期,把今天当作最后一天来计算,比如近一周,近一个月等
 * @param {Number}   period   日期(几天)
 * @param {Number}   time     时间戳
 * return ['yy-mm-dd', 'yy-mm-dd']  把今天作为最后一天往前推
 */
export const dateRangeGen = (period, time) => {
   
  const end = time ? new Date(time) : new Date()
  const start = end - 3600 * 1000 * 24 * period
  if (period === 1) {
   
    return [end, end].map(dateFormatter)
  }
  return [start, end].map(dateFormatter)
}

/**
 * dateNaturalRangeGen  自然周期(本周,本月,上月等)
 * @param {Number}   period      日期(几天)
 * @param {Number}   time        时间戳
 * @param {Boolean}  isThan      大于当前,是否获取
 * @param {Boolean}  timestamp   返回是否为时间戳
 * return ['yy-mm-dd', 'yy-mm-dd'] | ['1689609600000', '1689609600000']
 */
export const dateNaturalRangeGen = (period, time, isThan = false, timestamp = false) => {
   
  const {
    year, month, date, day } = dateParams()
  const end = time ? new Date(time) : new Date(year, month, isThan ? date : (date + (7 - day)))
  const days = isThan ? (day - 1) : (period - 1)
  const start = end - 3600 * 1000 * 24 * days
  if (period === 1) {
   
    return [end, end].map(el => timestamp ? new Date(el).getTime() : dateFormatter(el))
  }

  return [start, end].map(el => timestamp ? new Date(el).getTime() : dateFormatter(el))
}

export const pickerOptionGen = shortcuts => ({
   
  shortcuts: shortcuts.map(([text, period]) => ({
   
    text,
    onClick: picker => picker.$emit('pick', dateRangeGen(period))
  }))
})

/*
时间戳转换为日期
fmt: yyyy-MM-dd hh:mm:ss
*/
export const millisecondFormatDate = (time, fmt = 'yyyy-MM-dd hh:mm:ss') => {
   
  const date = time ? new Date(time) : new Date()
  const o = {
   
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) }
  for (const k in o) {
   
    if (new RegExp('(' + k + ')').test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) }
  }
  return fmt
}

export const getDateMapping = () => {
   
  const {
    year, month, date, day } = dateParams()
  const {
    endYear, endMonth, endDate } = dateStartAndLast(`${
     month ? year : year - 1}-${
     month || 12}-01`)
  const options = {
   
    1: {
    // 自定义,当前一周
      period: 7,
      time: 0
    },
    2: {
    // 本周,周一到当前日期前一天的23点
      period: day, // day,
      time: new Date(year, month, date)
    },
    3: {
    // 上周
      period: 7,
      time: new Date(year, month, date - day)
    },
    4: {
    // 上月
      period: endDate,
      time: new Date(endYear, endMonth, endDate)
    },
    5: {
    // 本月
      period: dateStartAndLast(`${
     year}-${
     month + 1}-01`).endDate,
      time: (() => {
   
        const {
    endYear, endMonth, endDate } = dateStartAndLast(`${
     year}-${
     month + 1}-01`)
        return new Date(endYear, endMonth, endDate)
      })()
    },
    9: {
    // 近一周
      period: 7,
      time: new Date(year, month, date)
    }
  }

  return {
   
    ...options,
    'week': options[2],
    'cweek': options[1], // 自定义-本周
    'pweek': options[3],
    'pmonth': options[4]
  }
}

export const pickerGen = shortcuts => ({
   
  shortcuts: shortcuts.map(([text, period]) => {
   
    const dateOptions = getDateMapping()
    const result = {
   
      'week': 'cweek' // 自定义 - 本周
    }[period] || period
    return {
   
      text,
      onClick: picker => picker.$emit('pick', dateNaturalRangeGen(dateOptions[result].period, dateOptions[result].time))
    }
  })
})

const dateShortcuts = [
  ['本周', 'week'],
  ['上周', 'pweek'],
  ['上月', 'pmonth']
]

export const pickerOption = pickerGen(dateShortcuts)

/*
  getPreviousDay 获取当前日期的前一天
  return yy-mm-dd
*/
export const getPreviousDay = (date = new Date()) => {
   
  const resetDate = new Date(date)
  const previous = new Date(resetDate.getTime())
  previous.setDate(resetDate.getDate() - 1)
  return dateFormatter(previous)
}

/**
 * diffTimeDay  时间差
 * @param  {Number}  startTime  开始时间戳
 * @param  {Number}  endTime    结束时间戳
*/
export function diffTimeDay(startTime, endTime) {
   
  const diffTime = endTime - startTime

  // 1天多少毫秒
  const daySecond = 24 * 3600 * 1000
  // 相差天数
  const day = Math.floor(diffTime / daySecond)

  // 1小时多少毫秒
  const hourSecond = 3600 * 1000

  // 相差小时数
  var dayRemainder = diffTime % daySecond // 计算天数后剩余的毫秒数
  var hour = Math.floor(dayRemainder / hourSecond)

  // 相差分钟数
  var hourRemainder = dayRemainder % hourSecond // 计算小时数后剩余的毫秒数
  var minute = Math.floor(hourRemainder / (60 * 1000))

  // 相差秒数
  var minuteRemainder = hourRemainder % (60 * 1000) // 计算分钟数后剩余的毫秒数
  var second = Math.round(minuteRemainder / 1000)

  return {
   
    day,
    hour,
    minute,
    second
  }
}

/**
 * 日期过滤器
 * @param   {String}  dateString
 * @returns {String}
 */
export function dateFilter(dateString) {
   
  const noTime = ['0000-00-00 0:0:0', '0000-00-00 00:00:00', '0001-1-1 0:0:0', '0001-1-1 00:00:00', '0001-01-01 0:0:0', '0001-01-01 00:00:00', '0000-00-00', '0001-01-01'].includes(dateString)

  if (noTime || !dateString && dateString !== 0) {
   
    return '-'
  }

  return dateString
}

export function parseTime(time, cFormat) {
   
  if (arguments.length === 0) {
   
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
   
    date = time
  } else {
   
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
   
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
   
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
   
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
   
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * hasDateBeenFormatted 格式化数据 判断是否含有year, month, day
 * @param  {String}  format  数据格式
 */

export const hasDateBeenFormatted = (format = 'yy-mm-dd hh:mm:ss') => {
   
  const result = format.toLocaleLowerCase()
  return {
   
    hasYear: result.includes('yy'),
    hasMonth: result.includes('-mm'),
    hasDay: result.includes('-dd'),
    hasHour: result.includes('hh'),
    hasMinute: result.includes(':mm'),
    hasSecond: result.includes(':ss')
  }
}

/**
 * formatDate 时间戳转化为年月日
 * @param {Number} time
 * @param {Sting} format
 * @returns
 */
export const formatDate = (time, format = 'YY-MM-DD') => {
   
  if (time < 0 || !time) {
   
    return []
  }
  const data = new Date(time)
  const year = data.getFullYear()
  const month = data.getMonth() + 1
  const day = data.getDate()
  const hour = data.getHours()
  const minute = data.getMinutes()
  const second = data.getSeconds()
  const {
    hasYear, hasMonth, hasDay, hasHour, hasMinute, hasSecond } = hasDateBeenFormatted(format)

  return {
   
    ...hasYear && year ? {
    year } : {
   },
    ...hasMonth && month ? {
    month: fillZero(month) } : {
   },
    ...hasDay && day ? {
    day: fillZero(day) } : {
   },
    ...hasHour && hour ? {
    hour: fillZero(hour) } : {
   },
    ...hasMinute && minute ? {
    minute: fillZero(minute) } : {
   },
    ...hasSecond && second ? {
    second: fillZero(second) } : {
   }
  }
}

/**
 * converTimeObjectToString  将时间对象转换为字符串
 * @param {String} time  时间
 */

export const converTimeObjectToString = (time, format = 'YY-MM-DD') => {
   
  const data = formatDate(time, format)
  const arrData = Object.keys(data)
  const dataLen = arrData.length - 1
  return arrData.reduce((acc, cur, index) => {
   
    const symbol = index < 2 ? '-' : index === 2 || index === dataLen ? ' ' : ':'
    return (acc += `${
     data[cur]}${
     symbol}`)
  }, '')
}

/**
 * converTimeStringToWeekArray  将时间字符串转换为周数组
 * @param {String} time  时间
 */
export const converTimeStringToWeekArray = time => {
   
  const data = new Date(time)
  const timesStamp = data.getTime()
  const currentDay = data.getDay()
  return Array
    .from(new Array(7), (value, index) => index)
    .reduce((acc, cur) => [
      ...acc,
      ...[
        new Date(timesStamp + 24 * 60 * 60 * 1000 * (cur - (currentDay + 7) % 7))
          .toLocaleDateString()
          .replace(/\//g, '-')
          .replace(/(\d+)/g, $1 => fillZero($1))
      ]
    ], [])
}

相关推荐

  1. 前端常用时间格式处理

    2024-01-27 20:44:01       42 阅读
  2. vue 中时间日期格式处理

    2024-01-27 20:44:01       22 阅读
  3. 前端时间格式传入后端负载里面没有东西

    2024-01-27 20:44:01       25 阅读
  4. Pythonjson格式处理

    2024-01-27 20:44:01       45 阅读
  5. gstreamer 常用图片格式转换命令

    2024-01-27 20:44:01       49 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-27 20:44:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-27 20:44:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-27 20:44:01       82 阅读
  4. Python语言-面向对象

    2024-01-27 20:44:01       91 阅读

热门阅读

  1. 简单计算器

    2024-01-27 20:44:01       55 阅读
  2. 【算法专题】动态规划之子序列问题

    2024-01-27 20:44:01       49 阅读
  3. 《微信小程序开发从入门到实战》学习九十四

    2024-01-27 20:44:01       61 阅读
  4. Spring Security Reactive

    2024-01-27 20:44:01       54 阅读
  5. 【Ubuntu】windows离线安装WSL2

    2024-01-27 20:44:01       51 阅读
  6. 讲清楚浅拷贝和深拷贝

    2024-01-27 20:44:01       64 阅读
  7. Day46 动态规划part08 139.单词拆分 多重背包

    2024-01-27 20:44:01       57 阅读
  8. SpringBoot 基础概念:注册BeanDefinition

    2024-01-27 20:44:01       70 阅读
  9. 低代码助力企业转型可视化

    2024-01-27 20:44:01       59 阅读