I am using the following functional Interface to make a general purpose custom date format converter.
@FunctionalInterface
public interface CustomDateFormatterInterface {
String convertStringToDate();
}
The Implementation of this functional Interface is as follows
CustomDateFormatterInterface customDateFormatterInterface = () -> {
LocalDateTime localDateTime = LocalDateTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ")
.withLocale(Locale.getDefault())
.withZone(ZoneId.systemDefault());
Instant now = Instant.now();
String formatted = dateTimeFormatter.format(localDateTime);
LocalDateTime parsed = dateTimeFormatter.parse(formatted, LocalDateTime::from);
return parsed.toString();
};
I want to get the following date format
2011-04-27T19:07:36+0000
. But I am getting an exception. If I try to use the now
Instant I am getting the output as
2020-12-29T15:44:34Z
What should I do can anyone tell me where I am going wrong? Let me know for any other things if needed.
use OffsetDateTime which has offset of the timezone and truncate it to seconds
A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00.
OffsetDateTime offsetDateTime = OffsetDateTime.now(ZoneId.of("Europe/Paris"));
offsetDateTime.truncatedTo(ChronoUnit.SECONDS).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); //2020-12-29T18:28:44+01:00
If you want a custom format the build it using DateTimeFormatterBuilder
OffsetDateTime offsetDateTime = OffsetDateTime.now(ZoneOffset.UTC);
DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.appendOffset("+HHMM", "+0000")
.toFormatter();
offsetDateTime.truncatedTo(ChronoUnit.SECONDS).format(dateTimeFormatter); //2020-12-29T17:36:51+0000