현재 타임 스탬프에서 3 주 빼기

Aug 20 2020

java.sql.Timestamp를 사용하여 현재 타임 스탬프-x 주 수를 어떻게 얻을 수 있습니까?

이것은 내 현재 타임 스탬프입니다. Timestamp.from(Instant.now(clock));

x-는 0-5 사이의 숫자 일 수 있습니다.

답변

4 Turing85 Aug 20 2020 at 20:47

제공된 코드를 보면 Instant비아 에서 주를 빼는 것이 좋습니다 Instant::minus. 에서 ChronoUnit.WEEKS지원되지 않기 때문에 Instant::minus7을 곱하여 주를 일 단위로 변환 할 수 있습니다.

변화하는 경우 Instant옵션이 아니다, 우리는을 변환 할 수 TimestampInstant, 빼기, 다시 변환 :

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

Ideone demo

또는 Optionals 의 친구 인 경우 :

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

Ideone demo

2 DigitShifter Aug 20 2020 at 21:41

Instant Directly 예제 사용, 현지 시간 사용 :

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

노트:

ChronoUnit.WEEKS를 직접 사용하지 않는 이유는 무엇입니까? 아래 참조 :

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

ChronoUnit.WEEKS는 java.time.Instant.minus 메소드에서 지원되지 않는 반면 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)
1 RahulMujnani Aug 20 2020 at 21:25

달력의 현재 시간에서 x 주를 빼려면 다음을 시도 할 수도 있습니다.

달력 달력 = Calendar.getInstance ();

calendar.add (Calendar.DAY_OF_MONTH,-(7 * no_of_weeks))