The front end converts the timestamp to the desired time format and day of the week

Title I think everyone may encounter the conversion of different time formats when doing development, especially when doing background management systems, many table queries will encounter the processing of time transfer parameters and time display. Let me share with you a processing method, welcome to exchange.

1. Encapsulate a function for time

parseTime (time, cFormat) {
    if (!time || 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
      if (typeof (time) === 'string') time = time.replace(/-/g, '/')
      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 timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
      let value = formatObj[key]
      if (key === 'a') return ['日','一', '二', '三', '四', '五', '六'][value]
      if (result.length > 0 && value < 10) {
        value = '0' + value
      }
      return value || 0
    })
    return timeStr
  }

2. Usage method
Pass in the object that needs to be converted, and the format you want to display
1. Display the year, month, and day
parseTime(1640618660,'{y}-{m}-{d}') Result: 2021-12-27
2 , display the year, month, day, hour, minute, second
parseTime(1640618660, '{y}-{m}-{d} {h}:{i}:{s}') result: 2021-12-27 23:24:20 3
. Display year, month, day, hour, minute, second and week
parseTime('2021-12-27 23:24:20','{y}-{m}-{d} {h}:{i}:{s} week {a} ') Result: 2021-12-27 23:24:20 Monday

Guess you like

Origin blog.csdn.net/tq1711/article/details/122133475