ISO 8601
If not homework, then use the standard ISO 8601 formats rather than devising your own.
The ISO 8601 standard includes the format PnYnMnDTnHnMnS
for a span of time not attached to the timeline. The P
marks the beginning and the T
separates years-month-days from hours-minutes-seconds.
Examples:
P4Y
is four years.
P1M15D
is a month and half.
PT1H30M
is an hour and a half.
java.time
The java.time classes supplant the troublesome old legacy date-time classes. The java.time classes use ISO 8601 formats by default when parsing and generating strings that represent date-time values.
Two classes represent a span of time unattached to the timeline. See Oracle Tutorial.
Search Stack Overflow to learn more, as your Question is really a duplicate of many others. Especially important to learn the limitations in java.time on this feature: Formatting a Duration in Java 8 / jsr310
You may want to track a span of time that is attached to the timeline. Use a pair of Instant
objects for that. The ThreeTen-Extra
project provides a java.time-savvy Interval
class for this purpose.
You can add or subtract a Period or Duration to/from a moment.
Instant.now()
.plus( Duration.parse( "PT5H" ) ); // Add 5 hours