-2

I have a solution for setting future/past date Java 8, but I would like to know if there is a cleaner way. I have a method in which one of the argument is of type ZonedDateTime.

I am extracting the time, converting to milliseconds and subtracting that from present now.

void setFuturePastDate(ZonedDateTime dateTime) {
    long diffInSeconds = ZonedDateTime.now().toEpochSecond() 
        - dateTime.toEpochSecond();
    Duration durationInSeconds = Duration.ofSeconds(diffInSeconds);
    Instant instantInSeconds = now.minusSeconds(durationInSeconds); 
    Clock clock = Clock.fixed(instantInSeconds, ZoneId.systemDefault());
    System.out.println(ZonedDateTime.now(clock)); // - I have a past date 

In Joda it was simple:

setCurrentMillisSystem(long)

and wherever we access new DateTime() it will give the date set.

Is there a cleaner way in Java 8 ?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Parameswar
  • 1,951
  • 9
  • 34
  • 57

2 Answers2

1
void setFuturePastDate(ZonedDateTime dateTime) {
    Clock clock = Clock.fixed(dateTime.toInstant(), ZoneId.systemDefault());
    System.out.println(ZonedDateTime.now(clock)); // - I have a past date 
}

This method prints the same ZonedDateTime as I passed in (provided it has the default zone).

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

If I understood you correctly, this is what you want:

void setFuturePastDate(LocalDateTime dateTime){
    final LocalDateTime now = LocalDateTime.now();
    final Duration duration = Duration.between(now, dateTime);
    final LocalDateTime mirrored;
    if(duration.isNegative()){
        mirrored = now.minus(duration);
    } else {
        mirrored = now.plus(duration);
    }

    System.out.println(mirrored);
}

This mirrors the dateTime around the now(). E.g: 5 days in the past becomes 5 days in the future.

Lino
  • 19,604
  • 6
  • 47
  • 65