3

The following script shows the relative time from now to 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>

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

nalzok
  • 14,965
  • 21
  • 72
  • 139

2 Answers2

5

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>
VincenzoC
  • 30,117
  • 12
  • 90
  • 112
3

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()
Marco Ferrantini
  • 381
  • 2
  • 10