定义 Java 常量日期的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7961698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to define Java constant dates
提问by fishtoprecords
I want define some constants, specifically a Date and Calendar that are before my domain can exist. I've got some code that works but its ugly. I am looking for improvement suggestions.
我想定义一些常量,特别是在我的域存在之前的日期和日历。我有一些有效的代码,但它很难看。我正在寻找改进建议。
static Calendar working;
static {
working = GregorianCalendar.getInstance();
working.set(1776, 6, 4, 0, 0, 1);
}
public static final Calendar beforeFirstCalendar = working;
public static final Date beforeFirstDate = working.getTime();
I'm setting them to July 4th, 1776. I'd rather not have the "working" variable at all.
我将它们设置为 1776 年 7 月 4 日。我宁愿根本没有“工作”变量。
Thanks
谢谢
采纳答案by Dave L.
I'm not sure I understand....but doesn't this work?
我不确定我是否理解....但这行不通吗?
public static final Calendar beforeFirstCalendar;
static {
beforeFirstCalendar = GregorianCalendar.getInstance();
beforeFirstCalendar.set(1776, 6, 4, 0, 0, 1);
}
public static final Date beforeFirstDate = beforeFirstCalendar.getTime();
回答by avh
I'd extract it to a method (in a util class, assuming other classes are going to want this as well):
我会将它提取到一个方法中(在一个 util 类中,假设其他类也需要这个):
class DateUtils {
public static Date date(int year, int month, int date) {
Calendar working = GregorianCalendar.getInstance();
working.set(year, month, date, 0, 0, 1);
return working.getTime();
}
}
Then simply,
那么简单地说,
public static final Date beforeFirstDate = DateUtils.date(1776, 6, 4);
回答by Rich
It might be clearer to use the XML string notation. This is more human readable and also avoids the local variable which you wanted to eliminate:
使用 XML 字符串表示法可能更清楚。这更具人类可读性,并且还避免了您想要消除的局部变量:
import javax.xml.bind.DatatypeConverter;
Date theDate = DatatypeConverter.parseDateTime("1776-06-04T00:00:00-05:00").getTime()