使用自定义字符串初始化静态最终日期 [英] Initialize static final Date using custom String
问题描述
我正在使用Java并遇到一个随机问题. 在这里,我共享了我的问题的示例代码.
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");
当我添加了上面代码中提到的try and catch时,它会引发错误
When I had added try and catch as mentioned in above code, it's throwing an error
变量"MAX_DATE"可能尚未初始化
Variable 'MAX_DATE' might not have been initialized
在使用下面的代码初始化时,它开始在第5行上抛出Cannot assign a value to final variable 'MAX_DATE'
错误.
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?
推荐答案
如果只需要一个简单的日期,则应使用LocalDate
而不是Date
:
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");
万一真的很难做到
- 具有从任意模式的String解析的日期,并且
- 使用良好的语言
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());
这篇关于使用自定义字符串初始化静态最终日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!