格式化消息距离时间(微信消息时间格式)

该篇文章介绍了JavaScript代码实现的`formatDistanceTime`函数,用于将给定的时间戳或时间字符串转换成微信消息中的时间显示格式,包括当前时间、昨天、本周内和不同年份的日期表达。
摘要由CSDN通过智能技术生成

使用效果

console.log(formatDistanceTime('2024-4-10 00:00:00')); // 凌晨0:00
console.log(formatDistanceTime('2024-4-10 06:00:00')); // 上午6:00
console.log(formatDistanceTime('2024-4-10 12:00:00')); // 中午12:00
console.log(formatDistanceTime('2024-4-10 14:00:00')); // 下午14:00
console.log(formatDistanceTime('2024-4-10 18:00:00')); // 晚上18:00
console.log(formatDistanceTime('2024-4-09 12:00:00')); // 昨天 中午12:00
console.log(formatDistanceTime('2024-4-08 12:00:00')); // 周一 中午12:00
console.log(formatDistanceTime('2024-4-06 12:00:00')); // 4月6日 中午12:00
console.log(formatDistanceTime('2023-4-06 12:00:00')); // 2023年4月6日 中午12:00

 代码

/**
 * 格式化消息距离时间(微信消息时间样式)
 * @param {number | string} timestamp 时间戳或时间字符串
 */
function formatDistanceTime(timestamp) {
  const now = new Date();
  const date = new Date(timestamp);

  const hours = date.getHours();
  const minutes = date.getMinutes();
  let period;
  if (hours < 6) {
    period = '凌晨';
  } else if (hours < 12) {
    period = '上午';
  } else if (hours < 13) {
    period = '中午';
  } else if (hours < 18) {
    period = '下午';
  } else {
    period = '晚上';
  }
  let baseTime = `${period}${hours}:${minutes < 10 ? '0' : ''}${minutes}`;

  // 当天
  if (
    date.getDate() === now.getDate() &&
    date.getMonth() === now.getMonth() &&
    date.getFullYear() === now.getFullYear()
  ) {
    return baseTime;
  }

  // 昨天
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  if (
    date.getDate() === yesterday.getDate() &&
    date.getMonth() === yesterday.getMonth() &&
    date.getFullYear() === yesterday.getFullYear()
  ) {
    return '昨天 ' + baseTime;
  }

  // 本周内
  if (
    date.getFullYear() === now.getFullYear() &&
    date.getMonth() === now.getMonth() &&
    date.getDate() >= now.getDate() - now.getDay() &&
    date.getDate() < now.getDate()
  ) {
    const dayOfWeek = date.getDay();
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return days[dayOfWeek] + ' ' + baseTime;
  }

  // 本年内
  if (date.getFullYear() === now.getFullYear()) {
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return `${month}月${day}日 ${baseTime}`;
  }

  // 不是本年
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${year}年${month}月${day}日 ${baseTime}`;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值