This question already has an answer here:
I want to have something like this:
public class Stream
{
public startTime;
public endTime;
public getDuration()
{
return startTime - endTime;
}
}
Also it is important that for example if the startTime it's 23:00 and endTime 1:00 to get a duration of 2:00.
Which types to use in order to accomplish this in Java?
tl;dr
Not possible. If you have only time-of-day, the clock stops at midnight. Without the context of dates, how do we know if you mean 1 AM on the next day, next week, or next decade?
So going from 11 PM to 1 AM means moving backwards in time 22 hours, running the hands of the clock counterclockwise. See the result below, a negative twenty-two hours.
Crossing midnight requires the larger context of date in addition to time-of-day (see below).
Instant.now()
.Duration.between
.Duration
object, extract a number of 24-hour days, hours, minutes, seconds, and fractional second in nanoseconds by calling the variousto…Part
methods.(b) Or, call
toString
to generate aString
in standard ISO 8601 format ofPnYnMnDTnHnMnS
.Example code, using pair of
Instant
objects.New Technology In Java 8+
We have new technology for this now built into Java 8 and later, the java.time framework.
java.time
The java.time framework is defined by JSR 310, inspired by the highly successful Joda-Time project, extended by the ThreeTen-Extra project, and described in the Oracle Tutorial.
The old date-time classes such as java.util.Date/.Calendar bundled with the earliest versions of Java have proven to be poorly designed, confusing, and troublesome. They are supplanted by the java.time classes.
Resolution
Other answers discuss resolution.
The java.time classes have nanosecond resolution, up to nine digits of a decimal fraction of a second. For example,
2016-03-12T04:29:39.123456789Z
.Both the old java.util.Date/.Calendar classes and the Joda-Time classes have millisecond resolution (3 digits of fraction). For example,
2016-03-12T04:29:39.123Z
.In Java 8, the current moment is fetched with up to only millisecond resolution because of a legacy issue. In Java 9 and later, the current time can be determined up to nanosecond resolution provided your computer’s hardware clock runs so finely.
Time-Of-Day
If you truly want to work with only the time-of-day lacking any date or time zone, use the
LocalTime
class.A
Duration
represents a span of time it terms of a count of seconds plus nanoseconds.Dump to console.
ISO 8601
Notice the default output of
Duration::toString
is in standard ISO 8601 format. In this format, theP
marks the beginning (as in 'Period'), and theT
separates any years-months-days portion from the hours-minutes-seconds portion.Crossing Midnight
Unfortunately, working with time-of-day only gets tricky when you wrap around the clock crossing midnight. The
LocalTime
class handles this by assuming you want to go backwards to an earlier point in the day.Using the same code as above but going from
23:00
to01:00
results in a negative twenty-two hours (PT-22H
).Date-Time
If you intend to cross midnight, it probably makes sense for you to be working with date-time values rather than time-of-day-only values.
Time Zone
Time zone is crucial to dates. So we specify three items: (1) the desired date, (2) desired time-of-day, and (3) the time zone as a context by which to interpret that date and time. Here we arbitrarily choose the time zone of the Montréal area.
If you define the date by only an offset-from-UTC, use a
ZoneOffset
with aOffsetDateTime
. If you have a full time zone (offset plus rules for handling anomalies such as Daylight Saving Time), use aZoneId
with aZonedDateTime
.We specify the later time as next day at 1:00 AM.
We calculate the
Duration
in the same manner as seen above. Now we get the two hours expected by this Question.Dump to console.
Daylight Saving Time
If the date-times at hand had involved Daylight Saving Time (DST) or other such anomaly, the java.time classes would adjust as needed. Read class doc for details.
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.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for
java.sql.*
classes.Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.It is worth noting that