我正在使用以下代码获取位置的时间和日期
dateAndTimeForAccount
如何检查reader.NextResult();
是否在早上6点到10点之间?
答案 0 :(得分:1)
一种可能的解决方案是使用ValueRange。
ZoneId zoneId = ZoneId.of("America/New_York");
ZonedDateTime dateAndTimeForAccount = ZonedDateTime.ofInstant(now, zoneId);
System.out.println(dateAndTimeForAccount);
ValueRange hourRange = ValueRange.of(8, 10);
System.out.printf("is hour (%s) in range [%s] -> %s%n",
dateAndTimeForAccount.getHour(),
hourRange,
hourRange.isValidValue(dateAndTimeForAccount.getHour())
);
示例输出
2017-01-11T07:34:26.932-05:00[America/New_York]
is hour (7) in range [8 - 10] -> false
答案 1 :(得分:0)
int currentHour = dateAndTimeForAccount.getHour();
boolean isBetween6And10 = 6 <= currentHour && currentHour <= 10;
如果要为任何特定的java.time类进行概括,可以使用TemporalQuery
类:
class HourTester extends TemporalQuery<Boolean> {
@Override
public Boolean queryFrom(TemporalAccessor temporal) {
int hour = temporal.get(ChronoField.HOUR_OF_DAY);
return 6 <= hour && hour <= 10;
}
}
用法:boolean isBetween6And10 = dateAndTimeForAccount.query(new HourTester());
答案 2 :(得分:0)
6 am
到10 am
独占之间这对于“ 99%” 的情况就足够了,因为“ you” 无法保证JVM时钟的精确度超过1毫秒。
return 6 <= t.getHour() && t.getHour() < 10;
6 to 10 am
之间 static final LocalTime OPEN_TIME = LocalTime.of(06, 00);
static final LocalTime CLOSE_TIME = LocalTime.of(10, 00);
return !t.toLocalTime().isBefore(OPEN_TIME) && !t.toLocalTime().isAfter(CLOSE_TIME);
6 to 10 am
之间 return t.toLocalTime().isAfter(OPEN_TIME) && t.toLocalTime().isBefore(CLOSE_TIME);
证明:
boolean isWithinSixToTen(ZonedDateTime t) {
return 6 <= t.getHour() && t.getHour() < 10;
}
import static org.assertj.core.api.Assertions.assertThat;
ZonedDateTime time(String time) {
return ZonedDateTime.parse("2017-01-11" + "T" + time + "-05:00[America/New_York]");
}
assertThat(isWithinSixToTen(time("10:01"))).isFalse();
assertThat(isWithinSixToTen(time("10:00"))).isFalse();
assertThat(isWithinSixToTen(time("09:59:59.999999999"))).isTrue();
assertThat(isWithinSixToTen(time("06:00"))).isTrue();
assertThat(isWithinSixToTen(time("05:59"))).isFalse();