Date() 时间的一个 format 格式化函数

本文介绍了一种实用的日期格式化方法,通过两个JavaScript函数实现不同场景下的日期格式转换。其中包括考虑年份是否相同的条件来调整输出格式,以及提供通用的格式化功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

const DATE_FORMAT = "YYYY-MM-DD hh:mm:ss";

export function taskDateFormat(targetDate) {
  if (targetDate) {
    const currentYear = new Date().getFullYear();
    const targetDateYear = new Date(targetDate).getFullYear();
    const format = currentYear !== targetDateYear ? "YYYY.MM.DD" : "MM.DD";
    return formatDate(targetDate, format);
  }
  return "";
}

/**
 * formatDate
 * @param {string | Date} date
 * @param {string} fmt "YYYY-MM-DD hh:mm:ss";
 * @return {string}
 */
export function formatDate(date, fmt = DATE_FORMAT) {
  if (typeof date === "string") date = new Date(date);
  if (!(date instanceof Date)) return "";
  const yearMatch = fmt.match(/(Y+)/);
  const yearFormat = yearMatch && yearMatch[1];
  if (yearFormat) {
    fmt = fmt.replace(
      yearFormat,
      `${date.getFullYear()}`.substring(4 - yearFormat.length, 4)
    );
  }
  let o = {
    "M+": date.getMonth() + 1,
    "D+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
  };
  for (let k in o) {
    const reg = new RegExp(`(${k})`);
    if (reg.test(fmt)) {
      let str = `${o[k]}`;
      const format = fmt.match(reg)[1];
      fmt = fmt.replace(format, format.length === 1 ? str : padLeftZero(str));
    }
  }
  return fmt;
}

function padLeftZero(str) {
  return ("00" + str).substring(str.length);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值