问题
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:
Change
protected static final Date MAX_DATE;
toprotected static final Date MAX_DATE = null;
and keep try-catch blockTo get rid of try-catch block - add
throws ParseException
betweenSample
and{
来源:https://stackoverflow.com/questions/63115630/initialize-static-final-date-using-custom-string