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
.