gpt4 book ai didi

java - 如何比较两个日期在 30 天内

转载 作者:行者123 更新时间:2023-12-03 21:56:27 24 4
gpt4 key购买 nike

当两个日期都在 30 天内时,我正在尝试将表单设置为特定逻辑。

Date fromDate = form.getFromDate();
Date toDate = form.getToDate();
if(fromDate.compareTo(toDate) > 30){ // if the selected date are within one month

}

我想添加类似验证以确保所选的两个日期在月份范围内

最佳答案

如果您有 Java 8 或更高版本,则此代码是理想的:

Instant fromInstant = fromDate.toInstant();
Instant toInstant = toDate.toInstant();
Duration duration = Duration.between(fromInstant, toInstant);
final Duration THIRTY_DAYS = Duration.ofDays(30);

if(duration.compareTo(THIRTY_DAYS) < 0) {
//Duration is less than thirty days
} else if(duration.compareTo(THIRTY_DAYS) > 0) {
//Duration is more than thirty days
} else {
//Duration is exactly thirty days.... somehow....
}

如果您需要一个“概念”月份(其持续时间可以从 28 到 31 天不等),而不是 30 天的确切数量,则此代码更好:

//Replace with the exact time zone of these dates
//if it's not the same as the time zone of the computer running this code.
ZoneId zoneId = ZoneId.systemDefault();

LocalDate fromLocalDate = LocalDate.ofInstant(fromDate.toInstant(), zoneId);
LocalDate toLocalDate = LocalDate.ofInstant(toDate.toInstant(), zoneId);
Period period = Period.between(fromLocalDate, toLocalDate);
final Period ONE_MONTH = Period.ofMonths(1);

if(period.compareTo(ONE_MONTH) < 0) {
//Difference is less than one month
} else if(period.compareTo(ONE_MONTH) > 0) {
//Difference is greater than one month
} else {
//Difference is exactly one month
}

关于java - 如何比较两个日期在 30 天内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48233470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com