Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the percent of time elapsed between two javascript dates

I'm trying to find how many days are left in a school year and return it as a jQuery UI progressbar.

jQuery UI progressbars only take percentages. How can I find the percentage of how far along I am in the timespan between two supplied dates, given today's date?

like image 821
Kyle Avatar asked Dec 29 '22 02:12

Kyle


2 Answers

Example: http://jsfiddle.net/FLaJM/4/

var start = new Date(2005,0,1),
    end = new Date(2021,0,1),
    today = new Date();

alert( Math.round(100-((end - start) * 100 ) / today) + '%' );

or if you wanted the percentage remaining:

Example: http://jsfiddle.net/FLaJM/3/

alert( Math.round(((end - start) * 100 ) / today) + '%' );
like image 112
user113716 Avatar answered Dec 31 '22 12:12

user113716


If you are using MomentJS, which I highly recommend for Javascript date stuff, you could do this:

var percentOfDayRangeComplete = function(start, end) {
    var now = moment();
    start = start || moment(now).startOf('day');
    end = end || moment(now).endOf('day');
    var totalMillisInRange = end.valueOf() - start.valueOf();
    var elapsedMillis = now.valueOf() - start.valueOf();
    // This will bound the number to 0 and 100
    return Math.max(0, Math.min(100, 100 * (elapsedMillis / totalMillisInRange)));
};

jsFiddle to see it in action...

like image 35
j.snyder Avatar answered Dec 31 '22 13:12

j.snyder