两个日期之间的时差和当前时间百分比

gnc*_*cnc 3 java date variable-assignment

我正在尝试使用线程建立一种计时机制,但在获取两个日期之间的时差并使用该时差获取当前剩余时间百分比时遇到了问题。这是我要尝试原型化的概念:

http://i.stack.imgur.com/wrsrF.png

这是我的实现:

long startMilisecs = System.currentTimeMillis();
long currentMilisecs;
long endDateMilisecs = getEndDate().getTime();
int diffMillisecs = ((int)(endDateMilisecs - startMilisecs) / 1000) / 60;
int currPerc; 
while (startMilisecs <= endDateMilisecs) 
{
    currentMilisecs = (int) System.currentTimeMillis();
    currPerc = ((int)currentMilisecs * 100) / diffMillisecs;
    System.out.println(" Current Percentage: " + currPerc);
}
Run Code Online (Sandbox Code Playgroud)

此代码的问题在于百分比不是从0开始,而是从20到40%。

你能告诉我这是怎么了吗?对于这个问题,我只能使用线程。

Bla*_*ker 6

检查以下:

 public static int getPercentageLeft(Date start, Date end) {
        long now = System.currentTimeMillis();
        long s = start.getTime();
        long e = end.getTime();
        if (s >= e || now >= e) {
            return 0;
        }
        if (now <= s) {
            return 100;
        }
        return (int) ((e - now) * 100 / (e - s));
    }
Run Code Online (Sandbox Code Playgroud)