First, it would be much better if your data source provided the time-of-day in standard ISO 8601 format using 24-hour clock, HH-MM-SS.
Even better, your data source should return the entire meaningful chunk of information, the date and the day-of-time and a time zone or offset altogether in standard ISO 8601 format, YYYY-MM-DDTHH:MM:SSZ. For example, 2016-09-26T21:57:18Z
where the Z
is short for Zulu and means UTC.
Anyways, to process your time-of-day values we must parse them. To parse, we must define a formatting pattern to match.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "hh:mm:ss aa" );
Loop your inputs, parsing each one, and collecting them. The LocalTime
class represents a time-of-day without a date and without a time zone.
List<LocalTime> times = new ArrayList<>();
…
LocalTime lt = LocalTime.parse( input , formatter );
…
Define your initial date. The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate initialDate = LocalDate.parse( "2014-05-13" );
Loop your collection of LocalTime
objects, combining each one with the LocalDate
to get a LocalDateTime
object.
LocalDateTime ldt = LocalDateTime.of( ld , lt );
But before combining, ask if the current LocalTime
is less than the previous, is earlier. If so, increment the LocalDate
.
if( lt.isBefore( previousLocalTime ) ) {
ld = ld.plusDays( 1 );
…
Keep in mind that these LocalDateTime
objects do not represent actual moments on the timeline. For an actual point in time, you must adjust them into a time zone (or offset).
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
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.