代码:
public static void main(String[] args) {
String date1="2021-01-05 12:00:00";
String date2="2021-01-01 12:00:00";
long daysBetween1= dayInterval(date1,date2);
System.out.println("天数差:"+daysBetween1);
long daysBetween2= dayInterval(date2,date1);
System.out.println("天数差:"+daysBetween2);
long timeBetween1= timeInterval(date1,date2);
System.out.println("毫秒差:"+timeBetween1);
long timeBetween2= timeInterval(date2,date1);
System.out.println("毫秒差:"+timeBetween2);
}
public static long dayInterval(String dateStart,String dateStop) {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
try {
Date d1=sdf.parse(dateStart);
Date d2=sdf.parse(dateStop);
long daysBetween=(d2.getTime()-d1.getTime()+1000000)/(60*60*24*1000);
return daysBetween;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public static long timeInterval(String dateStart,String dateStop) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date d1 = format.parse(dateStart);
Date d2 = format.parse(dateStop);
long diff = d2.getTime() - d1.getTime();
return diff;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}