1

I have this field

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'")
private Date completionDate;

I get this result: 2021-10-05T14:17:16Z

I need to split this date into 2 fields:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate date;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = ???)
@JsonDeserialize(using = LocalTimeDeserializer.class)
@JsonSerialize(using = LocalTimeSerializer.class)
private LocalTime time;

I know what I should use in the date part. But what pattern is needed for the time part? "HH:mm:ss'Z'"?

Pavel Petrashov
  • 1,073
  • 1
  • 15
  • 34

1 Answers1

0

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Do not mix the legacy and the modern Date-Time API: In your code, you have mixed the error-prone legacy Date-Time API with the modern Date-Time API which will make your code unnecessarily complex and error-prone. I recommend you declare completionDate as ZonedDateTime from which you can retrieve the Date and Time parts as shown in the following example:

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        ZonedDateTime completionDate = ZonedDateTime.now(ZoneId.of("Etc/UTC"));
        LocalDate date = completionDate.toLocalDate();
        LocalTime time = completionDate.toLocalTime();
        System.out.println(completionDate);
        System.out.println(date);
        System.out.println(time);

        // Some examples of custom formats
        DateTimeFormatter dtfTime = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.ENGLISH);
        System.out.println(time.format(dtfTime));

        DateTimeFormatter dtfDtTz = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX", Locale.ENGLISH);
        System.out.println(completionDate.format(dtfDtTz));
    }
}

Output:

2021-10-06T08:56:37.131679Z[Etc/UTC]
2021-10-06
08:56:37.131679
08:56:37
2021-10-06T08:56:37Z

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.


* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110