The parameterized constructors of the java.util.Date class are deprecated. What is the alternative?

Viewed 48608

What can I use to replace this, new Date(2009, 12, 9)?

Thanks for your help.

8 Answers

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*.

Also, quoted below is a notice at the Home Page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution using java.time, the modern API:

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        ZonedDateTime zdt = LocalDate.of(2009, 12, 9).atStartOfDay(ZoneId.of("Etc/GMT"));
        System.out.println(zdt);
    }
}

Output:

2009-12-09T00:00Z[Etc/GMT]

The Z in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).

For any reason, if you need to convert this object of ZonedDateTime to an object of java.util.Date, you can do so as follows:

Instant instant = zdt.toInstant();
Date date = Date.from(instant);

ONLINE DEMO

Like java.util.Date, an Instant represents an instantaneous point on the timeline in UTC, but unlike java.util.Date, which does not represent a real Date-Time object (a java.util.Date object simply represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT), it represents a real Date-Time object.

Learn more about java.time, the modern Date-Time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. 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 and How to use ThreeTenABP in Android Project.

Related