Reputation: 16107
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
.
Upvotes: 3
Views: 4411
Reputation: 31482
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>
Upvotes: 5
Reputation: 411
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()
Upvotes: 3