我有一个GregorianCalendar,我正在尝试设置时间。我从一个日历获取日期,从另一个日历获取时间。除了DST切换日的凌晨2点之外,它主要起作用。
例如,日期为3/10/2013,时间为2:40 AM,目标输出为3/10/2013 2:40 AM,我得到3/10/2013 3:40 AM:
GregorianCalendar reportingDate = //some instance with a relevant date (in this case 3/10/2013)
GregorianCalendar targetTime = //some instance with a relevant time (in this case 2:40AM)
Calendar combination = Calendar.getInstance();
combination.set(Calendar.YEAR, reportingDate.get(Calendar.YEAR));
combination.set(Calendar.MONTH, reportingDate.get(Calendar.MONTH));
combination.set(Calendar.DAY_OF_YEAR, reportingDate.get(Calendar.DAY_OF_YEAR));
combination.set(Calendar.HOUR, targetTime.get(Calendar.HOUR));
combination.set(Calendar.AM_PM, targetTime.get(Calendar.AM_PM));
combination.set(Calendar.MINUTE, targetTime.get(Calendar.MINUTE));
combination.set(Calendar.SECOND, targetTime.get(Calendar.SECOND));
一旦代码在组合日历上设置AM_PM,时间就会切换到凌晨3:40。我希望它不要切换。我认为这与目标时间日历被创建为纪元日期的时间有关,但我希望目标时间的具体日期并不重要......
答案 0 :(得分:1)
基于此输出......我认为这就是Java如何处理DST?好像2-3 AM似乎被遗忘了
请参阅下面的评论
final Calendar reportingDate = Calendar.getInstance();
reportingDate.set(Calendar.YEAR, 2013);
reportingDate.set(Calendar.MONTH, Calendar.MARCH);
reportingDate.set(Calendar.DAY_OF_MONTH, 10);
final Calendar targetTime = Calendar.getInstance();
targetTime.set(Calendar.AM_PM, Calendar.AM);
targetTime.set(Calendar.HOUR_OF_DAY, 3);
targetTime.set(Calendar.MINUTE, 0);
targetTime.set(Calendar.SECOND, 0);
targetTime.set(Calendar.MILLISECOND, 0);
final Calendar combination = Calendar.getInstance();
combination.set(Calendar.YEAR, reportingDate.get(Calendar.YEAR));
combination.set(Calendar.MONTH, reportingDate.get(Calendar.MONTH));
combination.set(Calendar.DAY_OF_YEAR, reportingDate.get(Calendar.DAY_OF_YEAR));
combination.set(Calendar.HOUR, targetTime.get(Calendar.HOUR));
combination.set(Calendar.AM_PM, targetTime.get(Calendar.AM_PM));
combination.set(Calendar.MINUTE, targetTime.get(Calendar.MINUTE));
combination.set(Calendar.SECOND, targetTime.get(Calendar.SECOND));
combination.set(Calendar.MILLISECOND, targetTime.get(Calendar.MILLISECOND));
final long timeAtCombined = combination.getTimeInMillis();
final SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSSZ");
sdf.setTimeZone(TimeZone.getTimeZone("US/Eastern"));
// subtract one minute
System.out.println(sdf.format(combination.getTime()));
combination.add(Calendar.MILLISECOND, -1);
System.out.println(sdf.format(combination.getTime()));
// millis @ 3
System.out.println(sdf.format(new Date(timeAtCombined)));
// millis @ 3 - 1ms
System.out.println(sdf.format(new Date(timeAtCombined - 1)));
输出
03/10/2013 03:00:00.000-0400
03/10/2013 01:59:59.999-0500
03/10/2013 03:00:00.000-0400
03/10/2013 01:59:59.999-0500
答案 1 :(得分:0)
您正在设置所有内容,时区(包含DST)除外。设置它,你应该没事。
答案 2 :(得分:0)
这不是直接回答你问题的答案,但你可以通过Joda Time
来避免所有这些疯狂他们真的把日期/时间/日历事情搞砸了。