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

如何将某个时间转换成距现在的时间,比如一分钟之内就显示“刚刚”,一小时内就显示“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
相关问题
HarmonyOS 如何将汉字转换成拼音
1255浏览 • 1回复 待解决
如何将AndroidAPP转换成鸿蒙
1850浏览 • 1回复 已解决
如何将时间转换为日期格式时间
4730浏览 • 1回复 待解决
如何将文件转换成字符串
1386浏览 • 1回复 待解决
请问如何将openblock文件转换成exe文件
3369浏览 • 0回复 待解决
HarmonyOS 日期如何转换成毫秒
983浏览 • 1回复 待解决
HarmonyOS 图片转换成ImageBitmap
1298浏览 • 1回复 待解决
HarmonyOS 如何将时间戳格式化
1288浏览 • 1回复 待解决
HarmonyOS 如何将时间进行格式化?
1418浏览 • 1回复 待解决
HarmonyOS 时间如何转换时间
856浏览 • 1回复 待解决
HarmonyOS 页面转换成图片
805浏览 • 1回复 待解决
如何base64转换成图片?
12120浏览 • 2回复 待解决
HarmonyOS json转换成对象
1298浏览 • 1回复 待解决
HarmonyOS Object怎么转换成map
1048浏览 • 1回复 待解决