How to make time.js show relative time in seconds?

The following script shows the relative time from now until 2017/07/03.

document.write(moment("20170703 00:00:00", "YYYYMMDD hh:mm:ss").fromNow());
<script src="https://cdn.bootcss.com/moment.js/2.17.1/moment.min.js"></script>
Run codeHide result

It returns something like in 5 months, while I expect something like in 123456789 seconds.

0
source share
2 answers

You can easily get the remaining seconds now:

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

You can get seconds between two instant objects using diff, specifying 'seconds'unit as the 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>
Run codeHide result

, (, fromNow()), relativeTimeThreshold relativeTime. :

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>
Hide result
+1

Source: https://habr.com/ru/post/1680660/


All Articles