package com.yu.bai.date;
import java.util.Calendar;
import java.util.Date;
public class TestDate2 {
public static void main(String[] args) {
//创建一个日期
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, -3);
Date date = calendar.getTime();
System.out.println(date);//此时获取的是当前时间往前推三天的日期
//调用方法,获得两个日期之间的时间差
double days = getDistanceTime(date,new Date());
System.out.println(days);
}
//计算时间差,以天数为单位。如:2018-08-08 和 2018-08-05 相差3天
public static int getDistanceTime(Date startTime, Date endTime) {
int days = 0;
long time1 = startTime.getTime();
long time2 = endTime.getTime();
long diff;
if (time1 < time2) {
diff = time2 - time1;
} else {
diff = time1 - time2;
}
days = (int) (diff / (24 * 60 * 60 * 1000));
return days;
}
//计算时间差,以小时为单位。如:2018-08-08 和 2018-08-07 相差24h
public double getDistanceTime2(Date startTime, Date endTime) {
double hour = 0;
long time1 = startTime.getTime();
long time2 = endTime.getTime();
long diff;
if (time1 < time2) {
diff = time2 - time1;
} else {
diff = time1 - time2;
}
hour = (diff / (60 * 60 * 1000));
return hour;
}
}
java实现两个日期的时间差
最新推荐文章于 2024-06-27 11:23:49 发布