I've created this program to calculate the time between startWork and finishWork
but I cant seem to figure out how to calculate time...
This is my Interface.
Just wanting to know a way of approaching this calculation.
Thanks
I've created this program to calculate the time between startWork and finishWork
but I cant seem to figure out how to calculate time...
This is my Interface.
Just wanting to know a way of approaching this calculation.
Thanks
Use java.time
as suggested by Ole V.V.
:
String time1 = "07:00:00";
String time2 = "15:30:12";
LocalTime t1 = LocalTime.parse(time1);
LocalTime t2 = LocalTime.parse(time2);
Duration diff = Duration.between(t1, t2);
System.out.println(diff.toString());
Prints:
PT8H30M12S
Use the Duration
class from java.time
to represent your working time. Let Duration.between()
do the calculation for you, passing two LocalTime
or two ZonedDateTime
objects to it as appropriate. The latter will take transitions to and from summer time (DST) into the calculation if such a transition happens during the working hours.
If the time is entered as for example 1530
or 3:30pm
, define a DateTimeFormatter
to parse it into LocalTime
.
Duration
objects can be summed using its plus
method, so you can calculate the hourly and monthly working time and so on.
To format the working time into for example 8.5
(for 8 hours 30 minutes), use the toMinutes
method, then convert to double
before you divide by 60 (I would declare the constant 60 as final double minutesPerHour = TimeUnit.HOURS.toMinutes(1);
).
java.time
is the modern Java date and time API. It came out nearly 4 years ago to replace the outdated and poorly designed date and time classes from Java 1.0 and 1.1 from the last years of the previous millennium.