1

I have a time variable

long time = (new Date()).getTime();

how would i perform a if statement on this? for example

if (time is over 5 minute)
    system.out.println("time is up")
else
   system.out.println("OK TIME")

Im looking to test the time to see that if it has been a minute since the variable was initialised then perform an if statement if the time has been over a certain amount.

1000111
  • 13,169
  • 2
  • 28
  • 37
prolog12345
  • 137
  • 1
  • 10

5 Answers5

2

Probably you are checking that the value of the variable "time" contains the milliseconds of 5 minutes earlier.

long time = (new Date()).getTime();

long currentTime = System.currentTimeInMillis();
long fiveMinutesInMilliSeconds = 5 * 60 * 1000L;

if((time + fiveMinutesInMilliSeconds) <= currentTime )
     System.out.println("Time's Up!);
else
     system.out.println("OK TIME")
1000111
  • 13,169
  • 2
  • 28
  • 37
0

To check difference of two Dates in minutes, use:

Date dateBefore = new Date();

//some computing...

Date dateAfter = new Date();

long timeInMinutes = (dateAfter.getTime()/60000) - (dateBefore.getTime()/60000);
if (timeInMinutes > 5) {
//something
} else {
//something
}

If you need more precise result (for some diagnostic, for example), you should use System.nanoTime().

vojta
  • 5,591
  • 2
  • 24
  • 64
0

Something like that:

public static void main(String[] args) throws IOException, InterruptedException {

    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.add(Calendar.MINUTE, 1);

    System.out.println(new Date());

    while(System.currentTimeMillis() < cal.getTimeInMillis()){
        System.out.println("not" + new Date());
        Thread.sleep(1000);
    }

    System.out.println("done"); 
}
pL4Gu33
  • 2,045
  • 16
  • 38
0

I think you can do this if you get two Calendar Instance:

Calendar variableInitialised = Calendar.getInstance();

After that you add your limit time to the instance,

variableInitialised.add(Calendar.MINUTE, 5);

And the you change your IF in something like that:

if(variableInitialised.after(Calendar.getInstance()))
Panchitoboy
  • 810
  • 9
  • 18
0

You need to take another 'startTime' variable which will indicate start time. Then you can calculate the difference between CurrentTime and StartTime. Use this difference inside 'if' clause.

                // has to be the time in past
                // Following constructor of Date is depricated. 
                // Use some other constructor. I added it for simplicity.
                long startTime = new Date(2015, 3, 3).getTime();
                long currentTime = new Date().getTime();

                long timeDiff = currentTime - startTime;
                long fiveMinutes = 300000; // 5 minutes in milliseconds
                if(timeDiff > fiveMinutes){
                    // TODO
                }