如何解决计算日期范围匹配到 Java
public String calculateSubscription(String email) {
Optional<Subscription> subscriptionsByUserEmail = subscriptionService.findSubscriptionsByUserEmail(email);
if (subscriptionsByUserEmail.isPresent()) {
Subscription subscription = subscriptionsByUserEmail.get();
LocalDateTime startAt = subscription.getStartAt();
LocalDateTime endAt = subscription.getEndAt();
LocalDateTime Now = LocalDateTime.Now();
if(/* do here comparison */){
return "subscribed";
}
}
return "unsubscribed";
}
到数据库中我存储了 2 个字段:
@Column(name = "start_at")
@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime startAt;
@Column(name = "end_at")
@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime endAt;
我需要检查 Now
变量是否在时间间隔 startAt
和 endAt
之间匹配。
如何在 if 语句中实现这种检查?
编辑:
@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime,Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime localDateTime) {
return Optional.ofNullable(localDateTime)
.map(Timestamp::valueOf)
.orElse(null);
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {
return Optional.ofNullable(timestamp)
.map(Timestamp::toLocalDateTime)
.orElse(null);
}
}
解决方法
两点:
- 不要在某个时间点使用
LocalDateTime
。任何阅读它的人都可以在他们能想到的任何时区自由地解释它,对于 24 到 26 小时的不同解释。Instant
是用于某个时间点的类。它和isBefore
一样有isAfter
和LocalDateTime
方法,所以代码不会有什么不同。也确实定义了时间点的替代方案包括ZonedDateTime
和OffsetDateTime
。 - 使用
Optional
时不要使用其isPresent
和get
方法(极少数情况除外)。它们是低级的,到目前为止,我们通常可以通过更高级别的方法获得更优雅的代码。
我更喜欢用 Optional
链接方法,所以我的代码看起来像:
public String calculateSubscription(String email) {
Instant now = Instant.now();
return subscriptionService.findSubscriptionsByUserEmail(email)
.filter(sub -> ! sub.getStartAt().isAfter(now) && sub.getEndAt().isAfter(now))
.map(sub -> "subscribed")
.orElse("unsubscribed");
}
这在 getStartAt()
和 getEndAt()
返回 Instant
时有效。为了在极端情况下获得一致的结果,我只读取了一次时钟(在过滤条件下不是两次)。时间间隔的标准解释是半开放的,从开始包含到结束不包含,所以我的代码使用它。我使用“not after”来表示“on or before”。在您的情况下,您可能不需要这种精度。
为了将时间点存储到您的数据库中,对于大多数数据库引擎,您需要一个 timestamp with time zone
。
如果可以且仅在可以的情况下确定时间点
编辑:详细说明一下,LocalDateTime
为我们提供的日期和时间,不要建立时间点。例如,东京的 6 月 30 日 11:45 比洛杉矶的 6 月 30 日 11:45 早 16 小时。因此,对于某个时间点,我们还需要时区或 UTC 偏移量。
如果您的数据库可以提供一个时间点,通常是通过前面提到的 timestamp with time zone
,我们很高兴。究竟如何将它检索到 Java 中取决于您的 JPA 版本和实现,所以我不想尝试在这一点上具体说明。您可能需要也可能不需要在 Java 中使用 OffsetDateTime
(甚至 ZonedDateTime
)而不是 Instant
或来提供与您不同的自定义转换器现在使用。后者可能使用 Timestamp::toInstant
而不是 Timestamp::toLocalDateTime
一样容易。
如果您的数据库只为您提供日期和时间,例如,如果它使用其 datetime
数据类型并且无法更改,请不要试图假装为其他方式。在这种情况下,坚持转换为 Instant
可能弊大于利。无论如何,没有任何链条比其最薄弱的环节更坚固。所以在这种情况下,在 Java 中始终坚持 LocalDateTime
。然后以这种方式读取时钟:
ZoneId timeZoneThatTheDatabaseAssumes = ZoneId.of("Europe/Gibraltar");
LocalDateTime now = LocalDateTime.now(timeZoneThatTheDatabaseAssumes);
当然要为您的数据库使用的时区指定时区 ID。
,您可以像下面这样使用 LocalDateTime#isAfter
和 LocalDateTime#isBefore
:
if (now.isAfter(startAt) && now.isBefore(endAt)) { .... }
,
这取决于要求。 @dariosicily 有道理,但如果年表或日历系统对您的应用程序很重要,那么建议使用 compareTo
LocalDateTime startAt = subscription.getStartAt();
LocalDateTime endAt = subscription.getEndAt();
LocalDateTime now = LocalDateTime.now();
if(now.compareTo(startAt) == 1 && now.compareTo(endAt) == -1){
return "subscribed";
}
,
您必须检查 now
是否介于 startDate
和 endDate
之间:
public String calculateSubscription(String email) {
Optional<Subscription> subscriptionsByUserEmail = subscriptionService.findSubscriptionsByUserEmail(email);
String result = "unsubscribed";
if(subscriptionsByUserEmail.isPresent()){
Subscription subscription = subscriptionsByUserEmail.get();
LocalDateTime startAt = subscription.getStartAt();
LocalDateTime endAt = subscription.getEndAt();
LocalDateTime now = LocalDateTime.now();
if (startAt.isBefore(now) && endAt.isAfter(now)) {
result = "subscribed";
}
}
return result;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。