# Remove Deprecated Date Constructs

# Description

Some java.util.Date constructors like new Date(int year, int month, int day), new Date(int year, int month, int date, int hrs, int min) and new Date(int year, int month, int date, int hrs, int min, int sec) are deprecated and the Calendar should be used instead. This rule searches for deprecated date constructors, introduces calendar instances, sets the time corresponding to the parameters in the deprecated constructor, and replaces the latter with an invocation of Calendar.getTime().

Note that the date constructor is implicitly adding 1900 to the first argument (i.e. year), whereas Calendar.set is expecting the exact year value. Therefore, the rule takes care of preparing the parameters of the Calendar.set properly.

If the deprecated constructor is used in a field initialization, then an initializer block is introduced for creating the calendar and initializing the field. See the examples below.

# Benefits

The major advantage of this rule is that you get rid of the long deprecated Date constructors.

# Tags

# Code Changes

# Year, Month, Day

Pre

Date date = new Date(99, 1, 1);

Post

Calendar calendar = Calendar.getInstance();
calendar.set(1999, 1, 1);
Date date = calendar.getTime();

# Year, Month, Day, Hour, Minutes

Pre

Date date = new Date(99, 2, 3, 4, 5);

Post

Calendar calendar = Calendar.getInstance();
calendar.set(1999, 2, 3, 4, 5);
Date date = calendar.getTime();

# Year, Month, Day, Hour, Minutes, Seconds

Pre

Date date = new Date(99, 2, 3, 4, 5, 6);

Post

Calendar calendar = Calendar.getInstance();
calendar.set(1999, 2, 3, 4, 5, 6);
Date date = calendar.getTime();

# Class Fields

Pre

class Foo {
    Date date = new Date(99, 1, 1);
}

Post

class Foo {
    Date date;
    {
        Calendar calendar = Calendar.getInstance();
        calendar.set(1999, 1, 1);
        date = calendar.getTime();
    }

}

# Limitations

Another deprecated java.util.Date constructor is new Date(String s) and is not handled by this rule.

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

Property Value
Rule ID DateDeprecated
First seen in jSparrow version 2.5.0
Minimum Java version 1.1
Remediation cost 1 min