若依日期格式化

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = 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
}

使用说明

定义好函数后传两个参数,第一个是 时间戳 或 new Date(),第二个是要转换的格式,非必传。

如 console.log(parseTime(new Date(), '{y}年{m}月{d}日 周{a} 时间{h}:{i}:{s}'))

花括号中会正则,对应年月日,周,时分秒,花括号外的作为自定义字符原样返回

 补充

  endOfStartTime: (startTime, endTime) => {
    let result = {
      day: '00',
      hou: '00',
      min: '00',
      sec: '00',
      signs: 0
    }

    if (endTime - startTime > 0) {
      const time = (endTime - startTime) / 1000 // 获取天、时、分、秒
      const day = parseInt(time / (60 * 60 * 24))
      const hou = parseInt(time % (60 * 60 * 24) / 3600)
      const min = parseInt(time % (60 * 60 * 24) % 3600 / 60)
      const sec = parseInt(time % (60 * 60 * 24) % 3600 % 60)
      result = {
        day: `${util.timeFormat(day)}`,
        hou: `${util.timeFormat(hou)}`,
        min: `${util.timeFormat(min)}`,
        sec: `${util.timeFormat(sec)}`,
        signs: 1
      }
    }

    return result
  },

传入开始时间戳和结束时间戳返回间隔时间 

  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值