专业编程教程与实战项目分享平台

网站首页 > 技术文章 正文

前端项目必备工具值得收藏——格式化时间

ins518 2024-10-09 16:26:05 技术文章 25 ℃ 0 评论

啰嗦的文字懒得敲 直接上代码

// 方法一
/**
 * 时间格式化
 * @param value
 * @param fmt 格式 eg:yyyy-MM-dd hh:mm:ss
 * @returns {*}
 */
export const formatDate = (value, fmt) => {
  var regPos = /^\d+(\.\d+)?$/
  if (regPos.test(value)) {
    // 如果是数字
    const getDate = new Date(value)
    const o = {
      'M+': getDate.getMonth() + 1,
      'd+': getDate.getDate(),
      'h+': getDate.getHours(),
      'm+': getDate.getMinutes(),
      's+': getDate.getSeconds(),
      'q+': Math.floor((getDate.getMonth() + 3) / 3),
      S: getDate.getMilliseconds()
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        (getDate.getFullYear() + '').substr(4 - RegExp.$1.length)
      )
    }
    for (const 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 fmt
  } else {
    value = value.trim()
    return value.substr(0, fmt.length)
  }
}

我还收藏了一个方法 是很早之前写的 很类似

/**
 * 时间格式化
 * @param value
 * @param cFormat 默认 "{y}-{m}-{d} {h}:{i}:{s}"
 */
export function formatTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  if (!time) return null;
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (("" + time).length === 10) time = parseInt(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;
}

供大家一起学习成长~~~

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表