java查两个日期之间的天数
时间: 2024-05-12 16:02:45 浏览: 51
要在Java中计算两个日期之间的天数,可以使用java.time包中的LocalDate类和ChronoUnit枚举。具体做法如下所示:
1. 导入所需的类和枚举:
```
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
```
2. 定义两个日期对象:
```
LocalDate date1 = LocalDate.of(2023, 4, 18);
LocalDate date2 = LocalDate.of(2023, 5, 10);
```
3. 使用ChronoUnit.DAYS.between()方法计算两个日期之间的天数:
```
long daysBetween = ChronoUnit.DAYS.between(date1, date2);
```
4. 打印结果:
```
System.out.println("相差天数: " + daysBetween);
```
完整的代码示例如下所示:
```java
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DateDifference {
public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2023, 4, 18);
LocalDate date2 = LocalDate.of(2023, 5, 10);
long daysBetween = ChronoUnit.DAYS.between(date1, date2);
System.out.println("相差天数: " + daysBetween);
}
}
```
你可以将你要比较的两个日期替换成具体的日期,运行代码后就可以得到它们之间的天数差。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [如何利用 Java 代码计算两个日期之间的天数?](https://blog.csdn.net/itcast_cn/article/details/130248721)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* [Java判断两个日期相差天数的方法](https://download.csdn.net/download/weixin_38546622/12802857)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文