最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get number of days as number in moment.js with x.fromNow(); - Stack Overflow

programmeradmin4浏览0评论

I use Moment.js

var created = moment("24.07.2015 16:09:05", "DD.MM.YYYY hh:mm:ss");
var expire= created.add(7, 'days');
var countdown = expire.fromNow();

var countdown gives me the string "in 3 days" - but how can I get only a number in days or in hours without the string "in days". I want to do a parison and mark the countdown in different colors, when its smaller than 7, or 4 or 1 day.

I use Moment.js

var created = moment("24.07.2015 16:09:05", "DD.MM.YYYY hh:mm:ss");
var expire= created.add(7, 'days');
var countdown = expire.fromNow();

var countdown gives me the string "in 3 days" - but how can I get only a number in days or in hours without the string "in days". I want to do a parison and mark the countdown in different colors, when its smaller than 7, or 4 or 1 day.

Share Improve this question edited Jul 28, 2015 at 19:16 Suisse asked Jul 28, 2015 at 19:04 SuisseSuisse 3,6336 gold badges40 silver badges72 bronze badges 3
  • I remend that you revise your question because at the moment it is a bit cryptic. – Alex Booker Commented Jul 28, 2015 at 19:11
  • @Petrichor I edited it. – Suisse Commented Jul 28, 2015 at 19:16
  • It makes way more sense now -- nice one! – Alex Booker Commented Jul 28, 2015 at 19:20
Add a ment  | 

1 Answer 1

Reset to default 10

Use moment.duration:

var created = moment("24.07.2015 16:09:05", "DD.MM.YYYY hh:mm:ss");
var expires = created.clone().add(7, 'days');

var now = new Date;
var dur = moment.duration({ from: now, to: expires });

console.log(dur.humanize()); // => "3 days"
console.log(dur.asDays()); // => 3.0729382175925926

This is exactly what fromNow does behind the scenes. You can use any Date or moment object for the from and to options, so if e.g. you want to get the time between now and expires, you would do moment.duration({ from: new Date, to: expires }).

发布评论

评论列表(0)

  1. 暂无评论