Youri
Youri

Reputation: 3

How to use time in calculations (half hours)

I want to make a program that's checking if an input is greater than 8h30m. How do I accomplish this? I thought maybe about java.util.Calendar or Date but I don't know how those things work.

Upvotes: 1

Views: 149

Answers (3)

Paulo
Paulo

Reputation: 1498

If what you want is to check if the current time is before another time, you can do this:

public Boolean foo() {
    Calendar currentlyCal = Calendar.getInstance(); // This is the currently time.
    Calendar calToCheck = Calendar.getInstance();
    calToCheck.set(Calendar.HOUR_OF_DAY, 8);
    calToCheck.set(Calendar.MINUTE, 30);
    return currentlyCal.before(calToCheck); // or use after() instead of before() if it's what you want.
}

EDIT

The difference:

public void getDifference(Calendar cal1, Calendar cal2) {
    long diff = cal2.getTimeInMillis() - cal.getTimeInMillis();
    long seconds = diff/1000;
    long hour = seconds/3600;
    seconds = seconds%3600;
    long minutes = seconds/60;
    seconds = seconds%60;
    // .. do something
}

Upvotes: 0

steffen
steffen

Reputation: 16948

Use the Duration from Java 8:

String input = "8h";
Duration duration = Duration.parse("PT" + input);
Duration compared = Duration.ofHours(8).plus(Duration.ofMinutes(30));
int compare = duration.compareTo(compared); // -1
// compare would be 0 for input="8h30m" and 1 for input="8h40m"

Edit - You can substract times as well, get the seconds for example:

Duration diff = duration.minus(compared);
int seconds = diff.getSeconds();

Upvotes: 1

user4198625
user4198625

Reputation:

Try using Joda Timer

http://www.joda.org/joda-time/

You can use DateTime for that and us function isAfter for your case.

Upvotes: 1

Related Questions