I'm troubleshooting an issue with converting a GregorianCalendar that only represents the current date (ie// 2013-03-10 00:00:00) to a java.util.Date object. The idea behind this test is to take two dates - one with only the current date, and one with only the current time (ie// 1970-01-01 12:30:45), and combine them into one date representing the Date and Time (2013-03-10 12:30:45).
On the day when the DST switch occured, the test failed - because converting the GregorianCalendar to a date object (Date date = dateCal.getTime(); in the code below) lost an hour and thus rolled back to (2013-03-09 23:00:00). How can I make this not happen?
public static Date addTimeToDate(Date date, Date time) {
if (date == null) {
throw new IllegalArgumentException("date cannot be null");
} else if (time == null) {
throw new IllegalArgumentException("time cannot be null");
} else {
Calendar timeCal = GregorianCalendar.getInstance();
timeCal.setTime(time);
long timeMs = timeCal.getTimeInMillis() + timeCal.get(Calendar.ZONE_OFFSET) + timeCal.get(Calendar.DST_OFFSET);
return addMillisecondsToDate(date, timeMs);
}
}
@Test
public void testAddTimeToDate() {
Calendar expectedCal = Calendar.getInstance();
Calendar dateCal = Calendar.getInstance();
dateCal.clear();
dateCal.set(expectedCal.get(Calendar.YEAR), expectedCal.get(Calendar.MONTH), expectedCal.get(Calendar.DAY_OF_MONTH));
Calendar timeCal = Calendar.getInstance();
timeCal.clear();
timeCal.set(Calendar.HOUR_OF_DAY, expectedCal.get(Calendar.HOUR_OF_DAY));
timeCal.set(Calendar.MINUTE, expectedCal.get(Calendar.MINUTE));
timeCal.set(Calendar.SECOND, expectedCal.get(Calendar.SECOND));
timeCal.set(Calendar.MILLISECOND, expectedCal.get(Calendar.MILLISECOND));
Date expectedDate = expectedCal.getTime();
Date date = dateCal.getTime();
Date time = timeCal.getTime();
Date actualDate = DateUtil.addTimeToDate(date, time);
assertEquals(expectedDate, actualDate);
}