javascript - How to make moment.js show relative time in seconds? - Stack Overflow

The following script shows the relative time from now to 20170703.document.write(moment("2017070

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=".js/2.17.1/moment.min.js"></script>

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./moment.js/2.17.1/moment.min.js"></script>

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

Share Improve this question asked Feb 14, 2017 at 1:57 nalzoknalzok 16.2k23 gold badges84 silver badges157 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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./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./ajax/libs/moment.js/2.16.0/moment.min.js"></script>

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()

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742311186a4419928.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信