Search code examples
javajava-8staticfinal

Initialize static final Date using custom String


I am working with Java and come through one random problem. Here I had shared sample code of my problem.

I want to initialize some of static final date field with my custom string format.

public class Sample {
    protected static final Date MAX_DATE ;
    static {
        try {
            MAX_DATE = new SimpleDateFormat("yyyy-MM-dd").parse("2099-12-31");
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }
}

While directly putting below line, it's asking for try and catch.

protected static final Date MAX_DATE= new SimpleDateFormat("yyyy-MM-dd").parse("2099-12-31");

When I had added try and catch as mentioned in above code, it's throwing an error

Variable 'MAX_DATE' might not have been initialized

While initialize with below code, it started throwing an error of Cannot assign a value to final variable 'MAX_DATE' on line number 5.

protected static final Date MAX_DATE=null;

Can somebody help me in this issue?


Solution

  • If you just need a plain date, you should use LocalDate instead of Date:

    protected static final LocalDate MAX_DATE = LocalDate.of(2099, 12, 31);
    

    If (for whatever reason) the date has to be taken from a String, you can also use it as follows:

    protected static final LocalDate MAX_DATE = LocalDate.parse("2099-12-31");
    

    In case it is really a hard requirement to

    • have the date parsed from String of arbitrary pattern and
    • use good ol' java.util.Date

    something like that should do the trick:

    protected static final Date MAX_DATE = Date.from(LocalDate.parse("2088||12||31", DateTimeFormatter.ofPattern("yyyy||MM||dd")).atStartOfDay(ZoneId.systemDefault()).toInstant());