Avoid Old Time Classes
You use the nasty old obsolete time classes associated with the earliest versions of Java. Use java.time classes instead.
Syntactic
Your input lines are almost in accordance with ISO 8601. Replace SPACE in the middle with T The java.time classes parse / generate strings according to ISO 8601 formats by default. Therefore, there is no need to specify a formatting pattern.
String startInput = "01/14/2012 09:29:58".replace( " " , "T" ); String stopInput = "01/15/2012 10:31:48".replace( " " , "T" );
LocalDateTime
Your entries are missing any information about offset-from-UTC or time zone. So, we analyze how LocalDateTime objects.
LocalDateTime startLdt = LocalDateTime.parse( startInput ); LocalDateTime stopLdt = LocalDateTime.parse( stopInput );
If you continue to work with these types, you will get results based on common 24-hour days, ignoring anomalies such as daylight saving time (DST).
If you know that the context of this data is a specific time zone, use the zone to get the ZonedDateTime .
ZoneId zoneId = ZoneId.of( "America/Montreal" ); ZonedDateTime start = startLdt.atZone( zoneId ); ZonedDateTime stop = stopLdt.atZone( zoneId );
If you want the current moment to start or stop, call now . Pass on your desired / expected time zone, rather than relying on a valid time zone JVMs.
ZonedDateTime now = ZonedDateTime.now( zoneId );
Duration
Duration class represents the time span as the total number of seconds plus the fraction of a second in the resolution of nanoseconds.
Duration duration = Duration.between( start , stop );
Oddly enough, in Java 8 this class has no methods for getting the number of days, hours, etc., that make up this period of time. Java 9 adds methods toβ¦Part .
long days = duration.toDaysPart(); int hours = duration.toHoursPart(); int minutes = duration.toMinutesPart();
Prior to Java 9, you can do the math yourself.
About java.time
The java.time framework is built into Java 8 and later. These classes supersede old inconvenient time classes such as java.util.Date , .Calendar and java.text.SimpleDateFormat .
The Joda-Time project, now in maintenance mode , advises switching to java.time.
To learn more, see the Oracle Tutorial . And search for qaru for many examples and explanations.
Most of the functionality of java.time will be ported back to Java 6 and 7 in ThreeTen-Backport and additionally implemented with Android capability in ThreeTenABP .
The ThreeTen-Extra project extends java.time with additional classes. This project is proof of possible future additions to java.time. Here you can find useful classes such as Interval , YearWeek , YearQuarter , etc.