momentjs: show fromNow in exact seconds

See the post in my blog

TLDR; if you want fromNow to display exact seconds instead of a few seconds ago, use the following one-time setting before the fromNow

moment.relativeTimeThreshold('ss', 0);

Background

moment.js is a popular library for parsing, validating, manipulating, and displaying dates and times in JavaScript.

Recently I met an issue related to the fromNow api. It only shows a few seconds ago when the timestamp is several seconds ago. I want it to be as exact as something like 10 seconds ago.

Someone recommends using another lib moment-duration-format for duration formatting. Someone recommends using moment.utc as a workaround.

But:

  1. I don't want to use another lib unless I have to, especially for such a small feature request.
  2. The moment.utc workaround doesn't work if the duration goes beyong 24 hours.

Solution

After some additional research, I found that fromNow supports setting thresholds, see here

An excerpt of the threshold table:

Range Key Sample Output
0 to 44 seconds s a few seconds ago
unset ss 44 seconds ago
45 to 89 seconds m a minute ago

By default moment only sets threshold s to be 44, so if the timestamp is 0~44 seconds ago, it will show a few seconds ago.

But you can set ss to be some value like 10, then if the timestamp is 10~44 seconds ago, it will show the exact second value.

Since I always want exact seconds, so I just set ss to be 0.

moment.relativeTimeThreshold('ss', 0);

You can see more details in Relative Time Thresholds

你可能感兴趣的:(momentjs: show fromNow in exact seconds)