Viv*_*vek 4 java calendar date
我想设定一年的年份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
}
}
Run Code Online (Sandbox Code Playgroud)
为了避免使用弃用的方法,我喜欢这样:
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
}
}
Run Code Online (Sandbox Code Playgroud)
我只是不认为这是解决这个问题的最佳方法.我必须先正确设置日历对象,然后从中获取日期对象,而早些时候我可以直接修改日期对象.
有人可以提出更好的方法吗?
| 归档时间: |
|
| 查看次数: |
6615 次 |
| 最近记录: |