admin管理员组

文章数量:1400722

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 }).

本文标签: javascriptGet number of days as number in momentjs with xfromNow()Stack Overflow