各种时间处理封装

/**
 * 格式化时间 例如:parseTime(new Date(), '{y}-{m}-{d}'),
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || '{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);
    }
    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(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value];
    }
    return value.toString().padStart(2, '0');
  });
  return time_str;
}

/**
 * 秒转换成hh:mm:ss格式
 * @param {Number} seconds 秒
 * @returns
 */
export function formatSeconds(seconds) {
  let hh = parseInt(seconds / 3600, 10);
  if (hh < 10) hh = `0${hh}`;
  let mm = parseInt((seconds - hh * 3600) / 60, 10);
  if (mm < 10) mm = `0${mm}`;
  let ss = parseInt((seconds - hh * 3600) % 60, 10);
  if (ss < 10) ss = `0${ss}`;
  return `${hh}:${mm}:${ss}`;
}

/**
 * 秒转换成h小时m分钟s秒格式
 * @param {Number} seconds 秒
 * @param {String} unit 转化单位 hour 小时 minute 分钟 unit 秒
 * @param {Boolean} rounding 是否四舍五入 超过30
 * @returns
 */
export function formatSeconds2(seconds, unit = 'second', rounding = false) {
  if (seconds === 0) {
    return unit === 'second' ? '0秒' : '0分钟';
  }

  let str = '';
  let h = parseInt(seconds / 3600, 10);
  let m = parseInt((seconds - h * 3600) / 60, 10);
  const s = parseInt((seconds - h * 3600) % 60, 10);

  if (unit === 'second') {
    str = `${h > 0 ? `${h}小时` : ''}${m > 0 ? `${m}分钟` : ''}${s > 0 ? `${s}秒` : ''}`;
  } else if (unit === 'minute') {
    if (rounding && s >= 30) {
      m += 1;
    }
    str = `${h > 0 ? `${h}小时` : ''}${m > 0 ? `${m}分钟` : ''}`;
  } else {
    if (rounding && m >= 30) {
      h += 1;
    }
    str = `${h > 0 ? `${h}小时` : ''}`;
  }

  return str;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值