js格式化时间间隔

需求

js计算时间间隔要求如下:

小于1分钟:刚刚        60
小于1小时:几分钟前    60*60
小于1天:几小时前      60*60*24
小于1周:几天前        60*60*24*7
小于1月:几周前        60*60*24*30
小于1年:几个月前      60*60*24*365
大于1年:几年前        60*60*24*365

具体实现

formatTimeFromNowZh-中文方法
formatTimeFromNowEn-英文方法

//1.中文方法
function formatTimeFromNowZh(time) {
  // if (("" + time).length === 10) {
  //   time = parseInt(time) * 1000;
  // } else {
  //   time = +time;
  // }
  const d = new Date(time);
  const now = Date.now();
  const diff = (now - d) / 1000;
  // console.log('formatTimeFromNowZh time', time,'diff',diff)
  if(diff < 0){//未来时间
    return time
  }
  if (diff < 60) {
    return "刚刚";
  } else if (diff < 3600) {
    return Math.floor(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.floor(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 7) {
    return Math.floor(diff / (3600 * 24))+"天前";
  }else if (diff < 3600 * 24 * 30) {
    return Math.floor(diff / (3600 * 24 * 7))+"周前";
  }else if (diff < 3600 * 24 * 365) {
    let m = Math.floor(diff / (3600 * 24 * 30))
    m = m==12?11:m
    return m+"月前";
  }else if (diff >= 3600 * 24 * 365) {
    return Math.floor(diff / (3600 * 24 * 365))+"年前";
  }else{
    return time
  }
}
//2.英文方法
function formatTimeFromNowEn(time) {
  // if (("" + time).length === 10) {
  //   time = parseInt(time) * 1000;
  // } else {
  //   time = +time;
  // }
  const d = new Date(time);
  const now = Date.now();
  const diff = (now - d) / 1000;
  if(diff < 0){//未来时间
    return time
  }
  if (diff < 60) {
    return "Just now";
  } else if (diff < 3600) {
    let suffix = Math.floor(diff / 60) > 1?"minutes ago":"minute ago"
    return Math.floor(diff / 60) +" "+suffix;
  } else if (diff < 3600 * 24) {
    let suffix = Math.floor(diff / 3600) > 1?"hours ago":"hour ago"
    return Math.floor(diff / 3600)+" " + suffix;
  } else if (diff < 3600 * 24 * 7) {
    let suffix = Math.floor(diff / (3600 * 24)) > 1?"days ago":"day ago"
    return Math.floor(diff / (3600 * 24))+" "+suffix;
  }else if (diff < 3600 * 24 * 30) {
    let suffix =Math.floor(diff / (3600 * 24 * 7)) > 1?"weeks ago":"week ago"
    return Math.floor(diff / (3600 * 24 * 7))+" "+suffix;
  }else if (diff < 3600 * 24 * 365) {
    let m = Math.floor(diff / (3600 * 24 * 30))
    m = m==12?11:m
    let suffix = m > 1?"months ago":"month ago"
    return m+" "+suffix;
  }else if (diff >= 3600 * 24 * 365) {
    let suffix = Math.floor(diff / (3600 * 24 * 30)) > 1?"years ago":"year ago"
    return Math.floor(diff / (3600 * 24 * 365))+" "+suffix;
  }else{
    return time
  }
}

本文为 程序员青阳 原创文章,遵循 CC BY-NC-SA 4.0 版权协议,转载请附上原文链接及本声明。

原文链接:https://heliufang.github.io/posts/31559881/index.html