tl;dr
ChronoUnit.HOURS.between(
LocalTime.parse( "08:00:00" ) ,
LocalTime.parse( "13:00:00" )
)
5
…or…
ChronoUnit.HOURS.between(
ZonedDateTime.of(
LocalDate.of( 2017 , Month.JANUARY , 23 ) ,
LocalTime.parse( "08:00:00" ) ,
ZoneId.of( "America/Montreal" )
) ,
ZonedDateTime.of(
LocalDate.of( 2017 , Month.JANUARY , 25 ) ,
LocalTime.parse( "13:00:00" ) ,
ZoneId.of( "America/Montreal" )
)
)
53
java.time
Modern approach uses the java.time classes.
LocalTime
The LocalTime
class represents a time-of-day without a date and without a time zone.
LocalTime start = LocalTime.parse( "08:00:00" ) ;
LocalTime stop = LocalTime.parse( "13:00:00" ) ;
Duration
Get a Duration
object to represent the span-of-time.
Duration d = Duration.between( start , stop ) ;
ChronoUnit
For number of hours, use ChronoUnit
.
long hours = ChronoUnit.HOURS.between( start , stop ) ;
Android
For Android, see the ThreeTen-Backport and ThreeTenABP projects. See last bullets below.
ZonedDateTime
If you want to cross days, going past midnight, you must assign dates and time zones.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime start = ZonedDateTime.of(
LocalDate.of( 2017 , Month.JANUARY , 23 ) ,
LocalTime.parse( "08:00:00" ) ,
z
) ;
ZonedDateTime stop = ZonedDateTime.of(
LocalDate.of( 2017 , Month.JANUARY , 25 ) ,
LocalTime.parse( "13:00:00" ) ,
z
) ;
long hours = ChronoUnit.HOURS.between( start , stop ) ;
See this code run live at IdeOne.com.
53
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?