1

I want to return the time in millisecond of the time until 20:00 on the next upcoming Wednesday or 20:00 on the next upcoming Saturday, depending on which is closest. I just don't know how to get the time in millisecond of each of these times.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
oopsie
  • 29
  • 2

1 Answers1

3

You can use :

LocalDateTime now = LocalDateTime.now();                  //Get current Date time
LocalDateTime nextSaturday = now                          //Get date time
        .with(TemporalAdjusters.next(DayOfWeek.SATURDAY)) //of next SATURDAY
        .with(LocalTime.of(20, 0));                       //at 20:00   

//Now you can use until with ChronoUnit.MILLIS to get millisecond betwenn the two dates
long millSeconds = now.until(nextSaturday, ChronoUnit.MILLIS);
//or             = ChronoUnit.MILLIS.between(now, nextSaturday);

System.out.println(now);          //2018-07-05T16:54:54.585789200
System.out.println(nextSaturday); //2018-07-07T20:00
System.out.println(millSeconds);  //183905414

With zone time you can use :

ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Paris"));//Or any zone time
ZonedDateTime nextSaturday = now
        .with(TemporalAdjusters.next(DayOfWeek.SATURDAY))
        .with(LocalTime.of(20, 0));
long millSeconds = ChronoUnit.MILLIS.between(now, nextSaturday);

System.out.println(now);           //2018-07-05T18:25:10.377511100+02:00[Europe/Paris]
System.out.println(nextSaturday);  //2018-07-07T20:00+02:00[Europe/Paris]
System.out.println(millSeconds);   //178489622

To check which is close Wednesday or Saturday you can use :

LocalDate saturday = LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
LocalDate wednesday = LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));

long result;
if(saturday.isBefore(wednesday)){
    result = getMillSecond(DayOfWeek.SATURDAY);
}
result = getMillSecond(DayOfWeek.WEDNESDAY);

Or as @Andreas suggest in comment you can use :

ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Paris"));
DayOfWeek day = EnumSet.range(DayOfWeek.WEDNESDAY, DayOfWeek.FRIDAY)
        .contains(now.getDayOfWeek()) ? DayOfWeek.SATURDAY : DayOfWeek.WEDNESDAY;
long result = getMillSecond(day);

and you can put one of the previous code in a method and call it based on the condition above :

public static long getMillSecond(DayOfWeek day){
    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Paris"));//Or any zone time
    ZonedDateTime nextSaturday = now
            .with(TemporalAdjusters.next(day))
            .with(LocalTime.of(20, 0));
    return ChronoUnit.MILLIS.between(now, nextSaturday);
}
Andreas
  • 154,647
  • 11
  • 152
  • 247
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140