Search code examples
javascriptdatemomentjscountdown

Get number of days as number in moment.js with x.fromNow();


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 comparison and mark the countdown in different colors, when its smaller than 7, or 4 or 1 day.


Solution

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