格式化日期,只显示最小的相对时间段,如50秒,1米,2小时,3d等

Format date to only show the least minimum relative time segment i.e 50s, 1m, 2h, 3d etc

本文关键字:50秒 1米 3d 时间段 2小时 日期 显示 格式化 相对      更新时间:2023-09-26

我试图显示基于unix时间戳的最小时间段。

的例子:

  1. "50秒前"应该是50秒。
  2. "65秒前"应该是1米,因为它的60秒是分。
  3. "65分钟前"应该是1小时,因为它的60分钟是以分钟为单位的。
  4. "25 hours ago" => 1d.
  5. "8 days ago" => 1w.
  6. …1个月
  7. …2y(年).

我已经尝试了一些库,比如moment

moment.unix(1440187622).fromNow()

,但返回一个"句子",但它不是我想要的。

任何想法?

你看了moment.js的持续时间了吗?你可以这样写一个函数:

function segment(duration) {
  return duration.years() > 0 ? duration.years() + 'y' :
    duration.months() > 0 ? duration.months() + 'mon' :
    // ...
    duration.seconds() > 0 ? duration.seconds() + 's' : '';
}
segment(moment.duration(moment.diff(moment(),moment.unix(1440187622))))