java.time
Can anyone suggest a better approach?
Yes, use the java.time classes.
Jon Skeet's answer was correct, but is now deprecated since the Joda-Time team advises switching to java.time classes.
MonthDay
and LocalTime
We can parse this input string as two separate objects: MonthDay
and a LocalTime
. The first, obviously, is the month and day of the month, but without any year, so this is not a complete date. The second is the time of day, but without any date and without any time zone.
String input = "Sep 21 12:34:56.123"; DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM dd HH:mm:ss.SSS" ); MonthDay md = MonthDay.parse ( input , f ); LocalTime lt = LocalTime.parse ( input , f ); System.out.println ( "md: " + md + " | lt: " + lt );
md: --09-21 | lt: 12: 34: 56.123
LocalDateTime
We can add in a year, mix completely and get LocalDateTime
.
LocalDateTime ldt = LocalDateTime.of( ld , lt );
ZonedDateTime
This is not the present moment, not a point on the timeline. Without a UTC-offset context or time zone, a LocalDateTime
does not make sense.
Apply ZoneId
to get ZonedDateTime
. Now we have a significant moment, a point on the timeline.
ZoneId z = ZoneId.of( "America/Montreal" ); ZonedDateTime zdt = ldt.atZone( z );
source share