Nick
Nick

Reputation: 2641

Adding two times together

So I want to compare times and after doing a quick google search and reading through the API I have not found any solutions. So here is my situation.
Say I have Time t and this is set to a certain time. I want to add 2 minutes to this time so t =+ 2 minutes. Then Time current will be set to the current time and I want to use the Time.compare(Time,Time) so check if t is greater or less than the current time. This is only pseudocode so far and I don't know how to add 2 minutes to a Time variable. If there are any other options that will work suggest them too :)

Upvotes: 0

Views: 1494

Answers (4)

Biraj Zalavadia
Biraj Zalavadia

Reputation: 28484

Try this method

public boolean isTimeGreaterThenCurrent(Time t) {
        long timeGiven = ((t.hour*60)*60) + (t.minute*60) + (t.second);
        long timeCurrent=0;
        Calendar c = Calendar.getInstance();
        timeCurrent = ((c.get(Calendar.HOUR_OF_DAY)*60)*60) + (c.get(Calendar.MINUTE)*60) + (c.get(Calendar.SECOND));

        if(timeGiven>timeCurrent){
            return true;
        }else{
            return false;
        }

    }

Upvotes: 0

Asha Soman
Asha Soman

Reputation: 1856

Try this

String myTime = "02:50";
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Date d = null;
try {
    d = df.parse(myTime);
    } catch (ParseException e) {
    }
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.MINUTE,10);
String newTime = df.format(cal.getTime());
System.out.println("New Time : " + newTime);

Upvotes: 0

Yogie Soesanto
Yogie Soesanto

Reputation: 172

learn this for date comparison

  Date date = new Date(98, 5, 21);
  Date date2 = new Date(99, 1, 9);

  // make 3 comparisons with them
  int comparison = date.compareTo(date2);
  int comparison2 = date2.compareTo(date);
  int comparison3 = date.compareTo(date);

  // print the results
  System.out.println("Comparison Result:" + comparison);
  System.out.println("Comparison2 Result:" + comparison2);
  System.out.println("Comparison3 Result:" + comparison3);

Comparison Result:-1

Comparison2 Result:1

Comparison3 Result:0

for adding minutes

Date jamBanding = new Date();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(jamBanding.getTime());

cal.add(cal.MINUTE, 2)

jamBanding = cal.getTime(); //here is the date now + 2 minute

Upvotes: 1

Vipul Purohit
Vipul Purohit

Reputation: 9827

Use Date4j library this will solve your problem with simple api.

Upvotes: 1

Related Questions