Java 计算时间差值分钟、
时间: 2023-09-23 15:11:30 浏览: 113
秒、小时、天数的方法
Java中计算时间差值可以使用Java.util.Date和Java.util.Calendar类。以下是计算时间差值的示例代码:
1. 计算分钟差值
```java
Date startDate = new Date(); // 开始时间
// do something...
Date endDate = new Date(); // 结束时间
long diffInMilliSeconds = endDate.getTime() - startDate.getTime();
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(diffInMilliSeconds);
```
2. 计算秒差值
```java
Date startDate = new Date(); // 开始时间
// do something...
Date endDate = new Date(); // 结束时间
long diffInMilliSeconds = endDate.getTime() - startDate.getTime();
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(diffInMilliSeconds);
```
3. 计算小时差值
```java
Date startDate = new Date(); // 开始时间
// do something...
Date endDate = new Date(); // 结束时间
long diffInMilliSeconds = endDate.getTime() - startDate.getTime();
long diffInHours = TimeUnit.MILLISECONDS.toHours(diffInMilliSeconds);
```
4. 计算天数差值
```java
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.setTime(startDate);
calendar2.setTime(endDate);
long diffInMilliSeconds = calendar2.getTimeInMillis() - calendar1.getTimeInMillis();
long diffInDays = TimeUnit.MILLISECONDS.toDays(diffInMilliSeconds);
```
阅读全文