如何将某个时间转换成距现在的时间

如何将某个时间转换成距现在的时间,比如一分钟之内就显示“刚刚”,一小时内就显示“xx分钟前”,一天内就显示“xx小时前”,昨天就显示“昨天”,其他时间显示具体的年月日

HarmonyOS
2024-07-05 17:49:36
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
单花红丝线
export function formatRelativeTime(datestr: string) {
  let date = new Date(datestr)
  const now = new Date();
  const seconds = (now.getTime() - date.getTime()) / 1000;

  if (seconds < 60) {
    return '刚刚';
  } else if (seconds < 60 * 60) {
    return Math.round(seconds / 60) + '分钟前';
  } else if (seconds < 60 * 60 * 24) {
    return Math.round(seconds / (60 * 60)) + "小时前";
    // return '今天';
  } else if (seconds < 60 * 60 * 24 * 2) {
    return "昨天"
  } else {
    // 超过一年的简化表示
    return formatISODateToYYYYMMDD(datestr);
  }
}

export function formatISODateToYYYYMMDD(isoDateString: string): string {
  if (isoDateString) {
    // 解析 ISO 格式的日期时间字符串为 Date 对象
    const date = new Date(isoDateString);

    // 从 Date 对象中提取年月日信息
    const year = date.getUTCFullYear();
    const month = String(date.getUTCMonth() + 1).padStart(2, '0'); // 月份从 0 开始,所以加 1,并使用 padStart 确保为两位数
    const day = String(date.getUTCDate()).padStart(2, '0'); // 使用 padStart 确保为两位数


    if (new Date().getFullYear() === year) {
      //今年
      return `${month}月${day}日`;
    }
    return `${year}年${month}月${day}日`;

  }
  return ""

}
分享
微博
QQ
微信
回复
2024-07-06 10:44:49
提问
该提问已有0人参与 ,帮助了0人