JavaScript 代码片段——计算时间距离

需求:给定一个过去某个时间的时间字符串,例如 “2023-09-07 11:33:23”,返回距当前时间的距离,例如 “XX小时前”、“XX分钟前”、“刚刚”、超过一天显示原本时间。

输入:time = “2023-09-07 11:33:23”
代码:

/**
 * 计算时间距离
 */
function showFormattedTime(time: string): string {
    
    
  const now = new Date()

  const diff = now.getTime() - new Date(time).getTime()

  if (diff > 24 * 60 * 60 * 1000) {
    
    
    return time
  }

  if (diff > 60 * 60 * 1000) {
    
    
    return Math.floor(diff / (60 * 60 * 1000)) + '小时前'
  }

  if (diff > 60 * 1000) {
    
    
    return Math.floor(diff / (60 * 1000)) + '分钟前'
  }

  return '刚刚'
}

返回:“21小时前”

猜你喜欢

转载自blog.csdn.net/dangfulin/article/details/132752634