简体   繁体   中英

Calculate percentage between two dates in JavaScript

I've been trying to calculate the percentage between two dates given the code from some questions here in StackOverflow but the code doesn't work correctly. This is the question: Get the percent of time elapsed between two javascript dates

var start = new Date(2015,6,1),
end = new Date(2015,12,1),
today = new Date();

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

I want to calculate the progress from the 1rst of june to the 1rst of december and I get "-7"

Please help! Thanks

 var start = new Date(2015,6,1),
 end = new Date(2015,11,1),
 today = new Date();

 //use Math.abs to avoid sign
 var q = Math.abs(today-start);
 var d = Math.abs(end-start);
 alert("Rounded: "+Math.round((q/d)*100) + "%");
 alert("Fraction: "+((q/d)*100) + "%");

Also read Ray Toal answer 6 is july not jun

你的问题是,6月是7月,而不是6月,所以你的答案是负面的。

Javascript计算从0到11的月份。一月是0,十二月是11.您指定了6月到12月,但输入了6和12。

Here you go:

var start = new Date(2015,6,1),
end = new Date(2015,12,1),
today = new Date();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM