js-工厂模式

不打扰是莪最后的温柔 提交于 2019-12-01 07:57:49

使用情况:输入时间,返回固定的格式

DateUtil: {
  // 获取date对象 可传字符串 兼容ios safari
    date (val) {
      if (!val) return false
      if (!val.getTime) {
        if (typeof val === 'number') return new Date(val)
        let arr = val.split(/[- : T /]/)
        arr[1] -= 1
        return new Date(...arr)
      } else {
        return val
      }
    },
    format (date, fmt) {
      date = this.date(date)
      let o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        // 'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
        'h+': date.getHours(), // 小时
        'H+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        'S': date.getMilliseconds() // 毫秒
      }
      let week = {
        '0': '\u65e5',
        '1': '\u4e00',
        '2': '\u4e8c',
        '3': '\u4e09',
        '4': '\u56db',
        '5': '\u4e94',
        '6': '\u516d'
      }
      let time = {
        '0': '\u51cc\u6668', // 上午
        '1': '\u4e0a\u5348', // 下午
        '2': '\u4e0b\u5348', // 晚上
        '3': '\u665a\u4e0a' // 凌晨
      }
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
      }
      if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '/u661f/u671f' : '/u5468') : '') + week[date.getDay() + ''])
      }
      if (/(T)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, time[parseInt(date.getHours() / 6)])
      }
      for (let 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 unescape(fmt.replace(/\/u/g, '%u'))
    }
  }
}

  

这样使用:

let time = dateTime.DateUtil.format(new Date(), 'yyyy-MM-dd hh:mm:ss')

  

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!