Initialize static final Date using custom String

半腔热情 提交于 2020-08-05 09:36:17

问题


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?


回答1:


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 LocalDate MAX_DATE = Date.from(LocalDate.parse("2088||12||31", DateTimeFormatter.ofPattern("yyyy||MM||dd")).atStartOfDay(ZoneId.systemDefault()).toInstant());



回答2:


You can:

  1. Change protected static final Date MAX_DATE; to protected static final Date MAX_DATE = null; and keep try-catch block

  2. To get rid of try-catch block - add throws ParseException between Sample and {



来源:https://stackoverflow.com/questions/63115630/initialize-static-final-date-using-custom-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!