我有一个设置为2年前的Calendar对象。我想通过添加小时来更新接近当前时间的日历对象,但不应超过当前时间。
例如,原始日期为June 24,2015- 11:20:52:200
当前时间为Jul 14,2016- 14:08:30:100
我希望将时间戳设为Jul 14,2016-13:20:52:200
如果需要,更新应该在几天内向后传播。如果原始时间为June 24,2015 00:20:50:200
,且当前时间为June 27,2015 00:15:20:100
,则需要获取June 26,2016 23:20:200
。
Java 8中是否存在提供此类功能的本机方法?
答案 0 :(得分:1)
java.util.Calendar
类现在被java.time框架取代,内置于Java 8及更高版本中。这些类取代了旧的麻烦日期时间类,例如java.util.Date
,.Calendar
和& java.text.SimpleDateFormat
。
要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。
大部分java.time功能都被反向移植到Java 6& ThreeTen-Backport中的7,并在ThreeTenABP中进一步适应Android。
LocalTime
LocalTime
类仅代表一个时间,没有日期且没有时区。
我们可以从您过去的日期时间和您当前的日期时间中提取LocalTime
并进行比较。如果过去LocalTime
与当前日期相同或更早,我们可以坚持使用当前日期时间并调整到过去的时间。如果过去的LocalTime
位于当前LocalTime
之后,那么我们必须使用昨天的日期。
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime pastZdt = ZonedDateTime.of( 2015 , Month.June, 24 , 11 , 20 , 52 , 200_000_000 , zoneId );
ZonedDateTime nowZdt = ZonedDateTime.now( zoneId );
LocalTime pastTOD = pastZdt.toLocalTime();
LocalTime nowTOD = nowZdt.toLocalTime();
ZonedDateTime target = null;
if( pastTOD.isAfter( nowTOD ) ) { // Use yesterday’s date.
target = ZonedDateTime.of( nowZdt.toLocalDate().minusDays( 1 ) , pastTOD , zoneId );
} else { // Else, the past time-of-day is same or ealier than today’s time-of-day, so use today's date.
target = ZonedDateTime.of( nowZdt.toLocalDate() , pastTOD , zoneId );
}
注意:由于Daylight Saving Time (DST)等异常情况,该特定时间可能无法在此特定日期生效。请务必阅读课程文档,以了解调整以解决此类困境的最终行为。这种行为可能会或可能不会满足您的需求(没有完美的补救措施)。
警告:上面的代码从未运行过。使用风险由您自己承担。如果您发现缺陷,请编辑修复。