从当前时间戳中减去3周

lnlaulya  于 2021-07-08  发布在  Java
关注(0)|答案(3)|浏览(391)

如何使用java.sql.timestamp获取当前时间戳-x周数;
这是我当前的时间戳 Timestamp.from(Instant.now(clock)); x-可以是0-5之间的任意数字

tjjdgumg

tjjdgumg1#

要从日历的当前时间中减去x周,还可以尝试:
calendar=calendar.getinstance();
calendar.add(calendar.day/u month,-(7*no/u weeks))

ni65a41a

ni65a41a2#

看到提供的代码,我建议从 Instant 通过 Instant::minus . 自 ChronoUnit.WEEKS 不支持 Instant::minus ,我们可以将周数乘以7来换算成天数。
如果更改 Instant 不是一个选项,我们可以转换 Timestamp 变成一个 Instant ,相减,并转换回:

Timestamp.from(timestamp.toInstant().minus(x * 7L, ChronoUnit.DAYS));

ideone演示
或者,如果你是 Optional 学生:

Optional.of(timestamp)
    .map(Timestamp::toInstant)
    .map(t -> t.minus(x * 7L, ChronoUnit.DAYS))
    .map(Timestamp::from);

ideone演示

mbskvtky

mbskvtky3#

使用即时消息示例,使用本地时间:

Instant.now(Clock.systemDefaultZone()).minus(numberOfWeeks * 7L, ChronoUnit.DAYS);

用于上下文:

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

注:
为什么不直接用呢?见下表:

Instant.now(Clock.systemDefaultZone()).minus(numberOfWeeks, ChronoUnit.WEEKS)

方法java.time.instant.minus似乎不支持chronounit.weeks,而enum chronounit.days则不支持。在java.time.instant.minus方法中使用chronounit.weeks时,会引发以下异常:

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)

相关问题