gncvnvcnc
gncvnvcnc

Reputation: 45

Difference between two dates and percentage of current time java

I'm trying to make a timing mechanism using threads, and I'm having a problem in getting the time difference between two Dates, and using that difference to get a current percentage of the time left. Here is the concept I'm trying to prototype:

https://i.sstatic.net/wrsrF.png

And here is my implementation:

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);
}

The problem with this code is that the percentage is not starting from 0 but rather in the 20's to 40 percent.

Can you tell me what is wrong with this? and for this problem I have been restricted to using only threads.

Upvotes: 3

Views: 3451

Answers (3)

BlackJoker
BlackJoker

Reputation: 3191

check below:

 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));
    }

Upvotes: 6

Hakan NIZAMOGLU
Hakan NIZAMOGLU

Reputation: 91

The problem is with the System.currentTimeMillis();. Taken from the javadoc:

public static long currentTimeMillis()

Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

See the description of the class Date for a discussion of slight discrepancies that may arise between "computer time" and coordinated universal time (UTC).

Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

So your current time in milliseconds is based on January 1, 1970 UTC, not on your start date.

You need to calculate current time by subtracting start time from the value that is given by System.currentTimeMillis();.

I am basically formulating your linked image here. Other alternative calculations can also be carried out.

Upvotes: 0

Keppil
Keppil

Reputation: 46229

You need to subtract the starting time like this

currPerc = ((currentMilisecs - startMilisecs) * 100) / diffMillisecs;

to get the correct percentage.

Upvotes: 1

Related Questions