Reputation: 155
I am trying to use DateTimeParser and DateTimeFormatter to format the date time. My requirement is to format the input string to "yyyy-MM-dd'T'HH:mm:ssZ" format irrespective of whether the input has milliseconds or not. I am using below code to parse the input. But so far I can get it working for only with or without milliseconds.
This is my method:
public static DateTime convertDateTime(String dateTime){
DateTimeParser parsers = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").getParser();
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(parsers ).toFormatter().withLocale(Locale.US).withChronology(ISOChronology.getInstanceUTC());
return DateTime.parse(dateTime,formatter);
}
Imports used :
import org.joda.time.DateTime;
import org.joda.time.chrono.ISOChronology;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
import org.joda.time.format.DateTimeParser;
I want my code to accept 2 different input forms(with or without milliseconds) and returns one DateTime without milliseconds.
Examples:
input can be:
2020-10-01T12:05:22.458-04:00
2020-10-01T12:05:22-04:00
Output:
2020-10-01T12:05:22-04:00
Any help on this will be greatly appreciated. Thanks!
Upvotes: 2
Views: 3087
Reputation: 298153
You are reinventing the ISO_ZONED_DATE_TIME
.
For this format, milliseconds are already optional. You only have to truncate them when present, to get your desired result. The format is even the standard, so the code is as simple as:
String[] samples = {
"2020-10-01T12:05:22.458-04:00",
"2020-10-01T12:05:22-04:00",
};
for(String s: samples) {
ZonedDateTime parsed = ZonedDateTime.parse(s).with(ChronoField.MILLI_OF_SECOND, 0);
System.out.println(parsed);
}
2020-10-01T12:05:22-04:00
2020-10-01T12:05:22-04:00
Note that I used MILLI_OF_SECOND
to make the solution more intuitive regarding your task of removing the milliseconds. Actually, milliseconds are just nanoseconds with a lower precision, so you could use the even simpler ZonedDateTime.parse(s).withNano(0)
, once it has been understood.
Or, as suggested by Ole V.V., ZonedDateTime.parse(s).truncatedTo(ChronoUnit.SECONDS)
, which might be even easier to grasp.
Upvotes: 4