zoukankan      html  css  js  c++  java
  • js时间格式化方法封装

    时间格式化

    /***
     * 13位时间戳格式化
     * @param time 13位时间戳
     * @param fmt
     * @returns {string}
     */
    export function formatTimestamp(time = 0, fmt = 'yyyy-MM-dd hh:mm:ss') {
      if(time === 0 || !time) {
        return ''
      }
    
      let date = new Date(time)
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length));
        }
      }
      return fmt;
    }

    日期格式化

    /**
     * 格式化日期时间
     */
    
    export function formatDatetime (date, fmt) {
      if(!date) {
        return ''
      }
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
      }
    
      let obj = {
        'M+': date.getMonth() + 1,
        'd+': date.getDay(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      }
    
      for (let key in obj) {
        if (new RegExp(`(${key})`).test(fmt)) {
          let str = obj[key] + ''
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str))
        }
      }
      return fmt
    }
    
    function padLeftZero (str) {
      return ('00' + str).substr(str.length)
    }
  • 相关阅读:
    poj3723Conscription
    hiho1304 24点
    hdu2089不要62
    hdu3555Bomb
    关于分割平面问题
    poj2976Dropping tests(01分数规划)
    linux命令行
    java内存不足
    如何设置jsp默认的编码为utf-8
    visul svn+花生壳
  • 原文地址:https://www.cnblogs.com/onlywu/p/14153964.html
Copyright © 2011-2022 走看看