warbio
warbio

Reputation: 466

Java if-statement currentTimeMillis, check if specific time has passed

I've ran into an odd problem. I'm trying to check if the current time is greater than powertimer. When I run the method the if-statement returns true even though powerup.getPowertimer() - System.currentTimeMillis() is greater than 0 which I tested by printing out the result.

this.powertimer = System.currentTimeMillis() + 10000;
public long getPowertimer() {
    return this.powertimer;
}

if ((powerup.getPowertimer()  - System.currentTimeMillis()) > 0) {
    System.out.println(powerup.getPowertimer() - System.currentTimeMillis());
    powerup.reversePower(player);
    expired.add(powerup);
}

Does anyone know how to fix this?

Upvotes: 3

Views: 2823

Answers (2)

aioobe
aioobe

Reputation: 421090

To check if current time has "passed" the powertimer timeout, you do

if (System.currentTimeMillis() > powerup.getPowertimer()) {
    ...
}

Note that your line:

if ((powerup.getPowertimer()  - System.currentTimeMillis()) > 0)

is equivalent to

if (powerup.getPowertimer() > System.currentTimeMillis())
                            ^
                            |
                wrong direction of inequality

Upvotes: 3

Bohemian
Bohemian

Reputation: 425198

You've got the subtraction around the wrong way. Do this:

if (System.currentTimeMillis() - powerup.getPowertimer() > 0)

Always remember this:

delta = final - initial

Thanks to my high school physics teacher Geoff Powell for this little gem I have used often in my life.

Upvotes: 1

Related Questions