我正在尝试设置java.util.Date的年份.
我需要解析的时间戳不包括年份所以我这样做了:
private static final SimpleDateFormat logTimeStampFormat =
new SimpleDateFormat("MMM dd HH:mm:ss.SSS");
boolean isAfterRefDate (String line, Date refDate) {
try {
Date logTimeStamp = logTimeStampFormat.parse(line);
logTimeStamp.setYear(2012); // But this is deprecated!
return logTimeStamp.after(refDate);
} catch (ParseException e) {
// Handle exception
}
}
为了避免使用弃用的方法,我喜欢这样:
private static final SimpleDateFormat logTimeStampFormat =
new SimpleDateFormat("MMM dd HH:mm:ss.SSS");
private static Calendar cal = Calendar.getInstance();
boolean isAfterRefDate (String line, Date refDate) {
try {
Date logTimeStamp = logTimeStampFormat.parse(line);
cal.setTime(logTimeStamp);
cal.set(Calendar.YEAR, 2012);
logTimeStamp = cal.getTime();
return logTimeStamp.after(refDate);
} catch (ParseException e) {
// Handle exception
}
}
我只是不认为这是解决这个问题的最佳方法.我必须先正确设置日历对象,然后从中获取日期对象,而早些时候我可以直接修改日期对象.
有人可以提出更好的方法吗?
解决方法:
Can someone suggest a better approach.
当然 – 尽量避免首先使用日期和日历.使用Joda Time代替,这要好得多.
在日期上设置年份本质上是模棱两可的操作 – 今年的时区是什么意思?如果您在2012年2月29日的前一天设定2013年,您会发生什么?
使用Joda Time将使您的代码在您真正期望的数据类型方面更加清晰.如果确实需要,您始终可以在API边界转换为日期和日历.
标签:java,date,calendar
来源: https://codeday.me/bug/20190530/1182051.html