java.time
public static void parseCustomFormat(String formatPattern, String dateTimeString) {
LocalDate today = LocalDate.now(ZoneId.of("Asia/Kolkata"));
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern(formatPattern)
.parseDefaulting(ChronoField.YEAR_OF_ERA, today.getYear())
.parseDefaulting(ChronoField.MONTH_OF_YEAR, today.getMonthValue())
.parseDefaulting(ChronoField.DAY_OF_MONTH, today.getDayOfMonth())
.toFormatter(Locale.ENGLISH);
LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeString, formatter);
System.out.format(Locale.ENGLISH, "%-19s -> %s%n", dateTimeString, parsedDateTime);
}
The above method will basically use day, month and/or year from the string if the pattern says it should, and use the corresponding values form today’s date if not. For example:
parseCustomFormat("HH:mm:ss", "08:05:05");
parseCustomFormat("yyyy-MM-dd'T'HH:mm:ss", "2015-11-23T21:41:45");
parseCustomFormat("MM H:mm", "10 20:58");
parseCustomFormat("yy d H:mm", "34 29 9:30");
When I ran this code today, the output was:
08:05:05 -> 2018-06-04T08:05:05
2015-11-23T21:41:45 -> 2015-11-23T21:41:45
10 20:58 -> 2018-10-04T20:58
34 29 9:30 -> 2034-06-29T09:30
Parsing will be apt to fail if the pattern contains a week year and/or week number, u
for year or a day of week. It will be sure to fail if it contains hour within AM or PM (lowercase h
as in the example in the question) and no AM/PM marker.
We have a legacy code which we have to support from Java1.6+
No big problem. I have run the above code on Java 7 with ThreeTen backport, the backport of java.time
to Java 6 and 7 (see the link at the bottom), so it should work on Java 6 too. If you need a java.util.Date
for your legacy code (and don’t want to upgrade it to java.time
just now), convert like this:
Instant inst = parsedDateTime.atZone(ZoneId.systemDefault()).toInstant();
Date oldfashionedDate = DateTimeUtils.toDate(inst);
System.out.format(Locale.ENGLISH, "%-19s -> %s%n", dateTimeString, oldfashionedDate);
With this change to the above code the output on my computer was:
08:05:05 -> Mon Jun 04 08:05:05 CEST 2018
2015-11-23T21:41:45 -> Mon Nov 23 21:41:45 CET 2015
10 20:58 -> Thu Oct 04 20:58:00 CEST 2018
34 29 9:30 -> Thu Jun 29 09:30:00 CEST 2034
Links