简体   繁体   中英

new Date(year,month,day) is deprecated

I have a class A_Class which one of it's constructor parameters is of type Date and when I try to initialize an object of the class in my main for example:

A_Class aClass = new A_Class( param1, param2, new Date(1995,01,04) );

The IDE tells me that this format of Date is deprecated.

Isn't there another way of directly passing a new date to the constructor or do I always have to do it like this:

final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
String dateInString1 = "1995-Jan-4";
Date dateInDate1 = formatter.parse(dateInString1);
A_Class aClass = new A_Class( param1, param2, dateInDate1 );

Wrong class

You are using a terrible date-time class that is now legacy. Supplanted years ago by the modern java.time classes.

LocalDate

For a date-only value without time-of-day and without time zone, use LocalDate .

LocalDate localDate = LocalDate.of( 1995 , 1 , 5 ) ;

Generate text in standard ISO 8601 format YYYY-MM-DD.

String output = localDate.toString() ;

Design your class to hold a LocalDate rather than a Date .

public class Employee 
{
    private String givenName, surName ;
    LocalDate whenHired ;

    // Constructor
    public Employee( String givenName , String surName , LocalDate whenHired ) 
    {
        …
    }

}

Example usage.

Employee alice = new Employee( "Alice" , "Anderson" , LocalDate.of( 1995 , Month.JANUARY , 4 ) ) ;

Octal literal

new Date(1995,01,04)

Do not start a literal integer with a zero unless you mean octal (base 8) rather than decimal (base 10).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM