我正在解决将仅表示当前日期(即// 2013-03-10 00:00:00)的 GregorianCalendar 转换为 java.util.Date 对象的问题。这个测试背后的想法是取两个日期——一个只有当前日期,一个只有当前时间(即// 1970-01-01 12:30:45),并将它们组合成一个代表日期的日期和时间 (2013-03-10 12:30:45)。
在 DST 切换发生的那一天,测试失败 - 因为将 GregorianCalendar 转换为日期对象(Date date = dateCal.getTime(); 在下面的代码中)损失了一个小时,因此回滚到 (2013-03-09 23:00:00)。我怎样才能让这不会发生?
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);
}