import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
public class Demo {
public static void main(String[] args) {
Calendar startDate = Calendar.getInstance();//最初起始时间
LocalDateTime startTime = LocalDateTime.of(startDate.get(Calendar.YEAR),startDate.get(Calendar.MONTH),startDate.get(Calendar.DAY_OF_MONTH),startDate.get(Calendar.HOUR),startDate.get(Calendar.MINUTE));
try {
TimeUnit.MINUTES.sleep(2);//睡眠2分钟 这里可以写业务代码 目前是模拟业务代码花费并处理的时间是2分钟
} catch (InterruptedException e) {
e.printStackTrace();
}
Calendar endDate = Calendar.getInstance();//结束时间
LocalDateTime endTime = LocalDateTime.of(endDate.get(Calendar.YEAR),endDate.get(Calendar.MONTH),endDate.get(Calendar.DAY_OF_MONTH),endDate.get(Calendar.HOUR),endDate.get(Calendar.MINUTE));
// 计算时间差
Duration duration = Duration.between(startTime, endTime);
// 转换为分钟
long minutes = duration.toMinutes();
long hours = duration.toHours();
// 输出结果
System.out.println("总共用时: "+ hours + " 小时 " + minutes + " 分钟!");
}
}
java操作起始日期和结束日期总共花费时间
最新推荐文章于 2024-08-16 23:08:28 发布