从秒到年:打造与过去日期相关的智能显示

如何格式化过去的日期?

在前端开发中,经常会遇到需要将过去的日期转换成易读的形式,比如"刚刚"、“几分钟前”、"几小时前"等。为了方便处理这种情况,我们可以使用一个自定义的JavaScript方法来实现日期的格式化。

方法介绍

下面是这个格式化过去日期的方法:

const formatPast = (date, type = "default", zeroFillFlag = true) => {
    
    
  // 获取当前时间和传入时间之间的时间差
  const currentTime = new Date().getTime();
  const afferentTime = new Date(date).getTime();
  const timeDifference = currentTime - afferentTime;

  // 根据时间差的不同范围返回不同的字符串表示
  switch (true) {
    
    
    case timeDifference < 10000:
      return "刚刚";
    case timeDifference < 60000:
      return `${
      
      Math.floor(timeDifference / 1000)}秒前`;
    case timeDifference < 3600000:
      return `${
      
      Math.floor(timeDifference / 60000)}分钟前`;
    case timeDifference < 86400000:
      return `${
      
      Math.floor(timeDifference / 3600000)}小时前`;
    case timeDifference >= 86400000 && type === "default":
      let countTime = Math.floor(timeDifference / 86400000);
      if (countTime >= 365) {
    
    
        return `${
      
      Math.floor(countTime / 365)}年前`;
      }
      if (countTime >= 30) {
    
    
        return `${
      
      Math.floor(countTime / 30)}个月前`;
      }
      return `${
      
      countTime}天前`;
    default:
      // 如果时间差超过一天,返回具体的日期表示
      const formattedDate = new Date(date);
      const Y = formattedDate.getFullYear();
      const M = formattedDate.getMonth() + 1;
      const D = formattedDate.getDate();
      const zeroFillM = zeroFillFlag ? M.toString().padStart(2, "0") : M;
      const zeroFillD = zeroFillFlag ? D.toString().padStart(2, "0") : D;

      if (type === "-" || type === "/" || type === ".") {
    
    
        return `${
      
      Y}${
      
      type}${
      
      zeroFillM}${
      
      type}${
      
      zeroFillD}`;
      }
      if (type === "年月日") {
    
    
        return `${
      
      Y}${
      
      zeroFillM}${
      
      zeroFillD}`;
      }
      if (type === "月日") {
    
    
        return `${
      
      zeroFillM}${
      
      zeroFillD}`;
      }
      if (type === "年") {
    
    
        return `${
      
      Y}`;
      }
  }
};

使用示例

const date1 = "2024-02-15T09:30:00"; // 过去的日期
const date2 = "2024-02-28T15:45:00"; // 过去的日期

console.log(formatPast(date1)); // 输出:15天前
console.log(formatPast(date2, "年月日")); // 输出:2024年02月28日

在上述示例中,我们传入了不同的过去日期,并使用不同的格式类型进行格式化。你可以根据自己的需要选择合适的格式类型。

结语

这个自定义的JavaScript方法可以帮助我们方便地将过去的日期格式化成易读的形式。通过灵活使用不同的格式类型,我们可以根据需求展示出符合用户期望的日期表示。

猜你喜欢

转载自blog.csdn.net/weixin_44590591/article/details/136534653