设置java日期的年份

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)

我只是不认为这是解决这个问题的最佳方法.我必须先正确设置日历对象,然后从中获取日期对象,而早些时候我可以直接修改日期对象.

有人可以提出更好的方法吗?

Jon*_*eet 5

有人可以建议更好的方法.

当然 - 尽量避免使用DateCalendar首先使用.相反,使用Joda Time,这要好得多.

将年份设置为a Date本身就是一个模糊的操作 - 今年的时区是什么意思?如果您在2012年2月29日的前一天设定2013年,您会发生什么?

使用Joda Time将使您的代码在您真正期望的数据类型方面更加清晰.如果确实需要,您可以随时转换为/从DateCalendarAPI边界转换.