public static void main(String[] args) {
Instant now = Instant.now(Clock.systemDefaultZone());
System.out.println("The time right now (local time): " + Timestamp.from(now));
long numberOfWeeks = 3L;
Instant minusXweeks = now.minus(numberOfWeeks * 7L, ChronoUnit.DAYS);
System.out.println("The time 3 weeks before now (local time): " + Timestamp.from(minusXweeks));
}
输出:
The time right now (local time): 2020-08-20 23:24:58.077223
The time 3 weeks before now (local time): 2020-07-30 23:24:58.077223
Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Weeks
at java.base/java.time.Instant.plus(Instant.java:861)
at java.base/java.time.Instant.minus(Instant.java:978)
at TestClass.main(TestClass.java:18)
3条答案
按热度按时间tjjdgumg1#
要从日历的当前时间中减去x周,还可以尝试:
calendar=calendar.getinstance();
calendar.add(calendar.day/u month,-(7*no/u weeks))
ni65a41a2#
看到提供的代码,我建议从
Instant
通过Instant::minus
. 自ChronoUnit.WEEKS
不支持Instant::minus
,我们可以将周数乘以7来换算成天数。如果更改
Instant
不是一个选项,我们可以转换Timestamp
变成一个Instant
,相减,并转换回:ideone演示
或者,如果你是
Optional
学生:ideone演示
mbskvtky3#
使用即时消息示例,使用本地时间:
用于上下文:
输出:
注:
为什么不直接用呢?见下表:
方法java.time.instant.minus似乎不支持chronounit.weeks,而enum chronounit.days则不支持。在java.time.instant.minus方法中使用chronounit.weeks时,会引发以下异常: