[JavaScript] custom formatting tools server time ---

1. Format time server returns

In general, when the rear end is not processed, then, we get the server response times are generally such:
Here Insert Picture Description
then directly take page display, of course, does not look good, so we can encapsulate a general-purpose tools for formatting a time , general-purpose refers not necessarily to be installed on the same chart format time, for different browser to return to the field it is not the same, so we also pass to kill; tools is that you can take the matter to the project directly, you can to achieve most of the needs of show you, look at the code word does not say

2. Package custom time format tools
2.1 Time format codes
module.exports = (time,format) => {
  let dataFmt = format || 'yyyy-MM-dd hh:mm:ss'  // 需要格式化的规则

  time = typeof(time) == 'number' ? time : new Date(time)  // 处理传入的time

  let fmt = {
    'y+': time.getFullYear(),   // 年份
    'M+': time.getMonth() + 1,  // 月份
    'd+': time.getDate(),  // 日
    'h+': time.getHours(),  // 小时
    'm+': time.getMinutes(),  // 分钟
    's+': time.getSeconds()  // 秒
  }

  for(let i in fmt){
    if (new RegExp('(' + i + ')').test(dataFmt)){
      dataFmt = dataFmt .replace(RegExp.$1, fmt[i].toString().length <= 1 ? '0' + fmt[i] : fmt[i] )
    }
  }
  return dataFmt 
}
2.2 Parameter Description
parameter name Parameter Type Parameter Description Whether will pass
time Number The formatted time required, the time stamp may be through new Date, may be passed directly to the unprocessed time Yes
format String You need to format the formatting rules, such as: "yyyy-MM-dd hh: mm: ss", follow each letter represents a sense, can not be customized letters no
2.3 Called

Here is a tool class, it is written in the ES Modules wording, if necessary can be introduced by using only Import, as follows:

import formatTime from '../../utils/format-time.js'  // 导入方式

formatTime(publishTime,'MM-dd yyyy hh:mm')  // 调用方式
2.4 Test Results

test:

formatTime(publishTime,'MM-dd yyyy hh:mm')

Here Insert Picture Description

formatTime(new Date(publishTime),'yyyy/MM/dd hh:mm:ss')

Here Insert Picture Description
Junior partner may have to go to the test, as long as year, month, day, hour corresponding to the letters do not make the line, such as: Year correspondence is that 字母y, do not own a mass chaos字母z

2.5 increase functionality

expand:

The main function is to learn how to add some tools, and can be used

Features:

① increase of the week

② increase the time period (morning / afternoon / early morning)

Description:

Use 字母wbehalf of the week;
use 字母zfor AM (6h - 12h), afternoon (13h - 23h), in the morning (0h - 5h) This time period can customize according to their own ideas;
as these to expand the field, so the default value is still 年-月-日 时-分-秒, We need to show if it can be passed in the corresponding field

Code (modified):

module.exports = (time, format) => {
  let data = format || 'yyyy-MM-dd hh:mm:ss' // 需要格式化的规则

  time = typeof(time) == 'number' ? time : new Date(time)

  let fmt = {
    'y+': time.getFullYear(), // 年份
    'M+': time.getMonth() + 1, // 月份
    'd+': time.getDate(), // 日
    'h+': time.getHours(), // 小时
    'm+': time.getMinutes(), // 分钟
    's+': time.getSeconds(), // 秒
    'w+': time.getDay(), // 星期(0为星期日)
    'z+': time.getHours(), // 上午/下午/凌晨
  }

  function tranWeek(week) {
    switch (week) {
      case 0:
        return "星期日";
      case 1:
        return "星期一";
      case 2:
        return "星期二";
      case 3:
        return "星期三";
      case 4:
        return "星期四";
      case 5:
        return "星期五";
      case 6:
        return "星期六";
        break;
    }
  }

  function timeSlot(hours) {
    let h;
    if (hours >= 6 && hours <= 12) {
      h = 0
    } else if (hours > 12 && hours <= 23) {
      h = 1
    } else {
      h = 2
    }
    switch (h) {
      case 0:
        return "上午";
      case 1:
        return "下午";
      case 2:
        return "凌晨";
        break;
    }
  }

  function transform(i) {
    if (i == 'w+') {
      return tranWeek(fmt[i])
    } else if (i == 'z+') {
      return timeSlot(fmt[i])
    } else {
      return fmt[i].toString().length <= 1 ? '0' + fmt[i] : fmt[i]
    }
  }

  for (let i in fmt) {
    if (new RegExp('(' + i + ')').test(data)) {
      data = data.replace(RegExp.$1, transform(i))
    }
  }
  return data
}

test:

formatTime(publishTime, 'yy-MM-dd ww | zz hh:mm')

Here Insert Picture Description

3. Conclusion

The desire to help you, the individual side dishes, such as the text has shortcomings, welcome advice, if you feel good to give a praise chant ~

over~

----------------
Disclaimer: This article is the original article CSDN bloggers "@Umbrella", and follow CC 4.0 BY-SA
copyright agreement, reproduced, please attach the original source and this link statement.
Original link: HTTPS: //blog.csdn.net/Umbrella_Um/article/details/103197964
----------------

Published 134 original articles · won praise 80 · views 30000 +

Guess you like

Origin blog.csdn.net/Umbrella_Um/article/details/103197964