JavaScript 工具方法集合

JavaScript 格式化传入的时间

2018-03-22  本文已影响0人  枫_d646
# 此处传入的 time 为秒数,然后返回一个 12:12:45 格式的时间

function formatTime(time) {
  if (typeof time !== 'number' || time < 0) {
    return time;
  }

  var hour = parseInt(time / 3600);
  time = time % 3600;
  var minute = parseInt(time / 60);
  time = time % 60;
  var second = parseInt(time);

  return ([hour, minute, second]).map(function (n) {
    n = n.toString();
    return n[1] ? n : '0' + n;
  }).join(':');
}

# 其余类型的根据需求相应的改就好
const dateFormat = (date, format = 'yyyy-MM-dd hh:mm:ss', readability = false) => {
  if (!date) {
    date = new Date()
  }
  if (typeof date === 'string' && /^\d+$/.test(date)) {
    date = new Date(+date)
  }

  if (typeof date === 'number') {
    date = new Date(date)
  }

  if (typeof date !== 'number' && !(date instanceof Date)) {
    date = date.replace(/年|月/g, '-').replace(/日/g, '')
    date = new Date(date)
  }

  const duration = Date.now() - date
  const level1 = 60 * 1000                // 1 分钟
  const level2 = 60 * 60 * 1000           // 1 小时
  const level3 = 24 * 60 * 60 * 1000      // 1 天
  const level4 = 3 * 24 * 60 * 60 * 1000  // 3 天
  if (readability && duration < level4) {
    let str = ''
    if (duration < level1) str = '刚刚'
    if (duration > level1 && duration < level2) str = `${Math.round(duration / level1)}分钟前`
    if (duration > level2 && duration < level3) str = `${Math.round(duration / level2)}小时前`
    if (duration > level3 && duration < level4) str = `${Math.round(duration / level3)}天前`
    return str
  }
  const o = {
    'M+': date.getMonth() + 1,  // 月份
    'd+': date.getDate(),       // 日
    'h+': date.getHours(),      // 小时
    'm+': date.getMinutes(),    // 分
    's+': date.getSeconds(),    // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, String(date.getFullYear()).substr(4 - RegExp.$1.length))
  }
  Object.keys(o).forEach(k => {
    if (new RegExp(`(${k})`).test(format)) {
      format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[ k ]) : ((`00${o[ k ]}`).substr((String(o[ k ])).length)))
    }
  })
  return format
}
上一篇 下一篇

猜你喜欢

热点阅读