Vivek Vivek - 2 months ago 7
Java Question

Set the year of a java date

I am trying to set the year of a

java.util.Date
.

he time stamp I need to parse does not include the year so I did this:

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
}
}


To avoid using a deprecated method, I do like this:

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
}
}


I just don't think that this is the best way to solve this problem. I have to first set the calendar object properly and then get the date object back from it while earlier I could just modify the date object directly.

Can someone suggest a better approach?

Answer

Can someone suggest a better approach.

Sure - try to avoid using Date and Calendar in the first place. Use Joda Time instead, which is much better.

Setting the year on a Date is an inherently ambiguous operation - what time zone is this year meant to be? What would you expect to happen if you're setting a year of 2013 on a previous date of February 29th 2012?

Using Joda Time will make your code much clearer in terms of what kind of data you're really expecting. You can always convert to/from Date and Calendar at API boundaries if you really need to.