Benny Bottema Benny Bottema - 6 months ago 26
Java Question

What is the purpose of this code? Is it just duplicating a Date?

I came across an ancient piece of code by someone who doesn't work in the company anymore.

I'm wondering what the purpose is of this calendar magic:

if (value instanceof Date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime((Date) value);
return new Date(calendar.get(Calendar.YEAR) - 1900, calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));

It seems to me this would return a new
object with the same values as the original
. Is there some Calendar initialization going on that I'm missing? If the purpose is to return a new object with the same value, I would assume
does the job:

(Date) originalDate.clone()
// or
new Date(originalDate.getTime())

Version control shows the code never changed. Are there possible side effects of pulling the date through a Calendar first?


It is nothing more than an outdated way to remove hours, minutes and seconds from your initial date.

As you can see in this simple example:

Date value = new Date();
System.out.printf("Before %s%n", value);
Calendar calendar = Calendar.getInstance();
    "After %s%n", 
    new Date(
        calendar.get(Calendar.YEAR) - 1900, 


Before Thu Oct 06 11:19:26 GMT 2016
After Thu Oct 06 00:00:00 GMT 2016