争取时间直到特定的时间点

时间:2018-07-05 15:45:13

标签: java date timer calendar

我想返回下一个即将到来的millisecond的{​​{1}}或下一个即将到来的20:00的{​​{1}}之前的时间Wednesday最接近的。我只是不知道如何在每个时间的20:00中获得时间。

1 个答案:

答案 0 :(得分:3)

您可以使用:

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

使用时区时间,您可以使用:

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

要检查WednesdaySaturday附近的价格,您可以使用:

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);

或者按照@Andreas在评论中的建议,您可以使用:

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);

,您可以将前面的代码之一放入方法中,然后根据上述条件调用它:

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);
}