Skip to content Skip to sidebar Skip to footer

How To Make Moment.js Show Relative Time In Seconds?

The following script shows the relative time from now to 2017/07/03. It returns something like in 5 months, while I expect something like in 123456789 seconds.

Solution 1:

You can get seconds between two moment objects using diff specifing 'seconds' unit as second parameter:

var mom = moment("20170703 00:00:00", "YYYYMMDD HH:mm:ss");
document.writeln(mom.fromNow());
document.writeln(mom.diff(moment(), 's'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>

If you need to customize how moment shows relative time (e.g. the fromNow() output) you can use relativeTimeThreshold and relativeTime. Here an example:

var mom = moment("20170703 00:00:00", "YYYYMMDD HH:mm:ss");
console.log(mom.fromNow());

// Change relativeTimeThreshold
moment.relativeTimeThreshold('s', 60*60*24*30*12);

moment.updateLocale('en', {
  relativeTime : {
    s: function (number, withoutSuffix, key, isFuture){
      return number + ' seconds';
    },
  }
});

console.log(mom.fromNow());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>

Solution 2:

You can easily get the seconds left from now in this way:

var seconds = moment("20170703 00:00:00", "YYYYMMDD hh:mm:ss").unix() - moment().unix()

Post a Comment for "How To Make Moment.js Show Relative Time In Seconds?"