Via javascript, I want to generate the percentage plete between these two days based on today and I will use this percentage on a jQuery UI progress bar to indicate the time plete or left.
I have tried this formula but I end up always getting 100:
Assume I have two dates:
start = new Date(2012,6,2); // Jul 02 2012
end = new Date(2012,6,8); // Jul 08 2012
today = new Date();
alert( Math.round(100-((end - start) * 100 ) / today) + '%' );
How can I achieve this correctly?
Via javascript, I want to generate the percentage plete between these two days based on today and I will use this percentage on a jQuery UI progress bar to indicate the time plete or left.
I have tried this formula but I end up always getting 100:
Assume I have two dates:
start = new Date(2012,6,2); // Jul 02 2012
end = new Date(2012,6,8); // Jul 08 2012
today = new Date();
alert( Math.round(100-((end - start) * 100 ) / today) + '%' );
How can I achieve this correctly?
Share Improve this question edited Jul 6, 2012 at 13:46 Hellnar asked Jul 6, 2012 at 13:38 HellnarHellnar 65k82 gold badges208 silver badges282 bronze badges 6-
2
Why bother to instantiate dates at all? Just use those raw numbers, and then get the current time from your current date with
.getTime()
– Pointy Commented Jul 6, 2012 at 13:39 - I just get these numbers in Unix timestamp from my server, actually you can ignore the initiation example dates. – Hellnar Commented Jul 6, 2012 at 13:41
- Just fixed the example time instantiates. – Hellnar Commented Jul 6, 2012 at 13:43
- @Hellnar the ments don't match the code. – EricG Commented Jul 6, 2012 at 13:45
- @EricG Thank you Eric, fixed code according to the ment. – Hellnar Commented Jul 6, 2012 at 13:47
3 Answers
Reset to default 4Since you get unix timestamps from server, you can just do this
var start = 1341201600 * 1000,
end = 1341720000 * 1000,
now = +new Date;
Math.round(( ( now - start ) / ( end - start ) ) * 100) + "%" //73%
I took the liberty to adjust the ment.
var start = new Date(2012,6,2); // Jul 02 2012
var end = new Date(2012,8,2); // Sep 02 2012
var today = new Date();
var total = end - start;
var progress = today - start;
console.log( Math.round(progress/ total * 100 ) + "%" );
Yields 8% [ 6th of July ]
Your formula should be
alert( Math.round(100 - (end - today) / (end - start) * 100 ) + '%' );