The Answer by Soshin is good. But personally I would work with the date and the time separately.
LocalDate
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern( "uuuuMMdd" );
LocalDate ld = LocalDate.parse( "20160101" , dateFormatter );
LocalTime
And the time-of-day. No need for the AM/PM part; the formatting code indicates whether the expected time-of-day is in 12-hour time or 24-hour time.
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern( "hhmm" ); // hh = two digits of 12-hour time (1-12). mm = minute-of-hour.
LocalDate ld = LocalDate.parse( hours + minutes , timeFormatter ); // 0545 in afternoon.
LocalDateTime
You can combine them into a LocalDateTime
.
LocalDateTime ldt = LocalDateTime.of( ld , lt );
ZonedDateTime
If you know for certain the intended time zone of this value, apply a ZoneId
to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ldt.atZone( z );
A LocalDateTime
has no meaning; it is not an actual moment without the context of an offset-from-UTC or a time zone. A ZonedDateTime
in contrast is indeed an actual point on the timeline.
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
, & 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. Specification is JSR 310.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
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.