只计算相差多少天,忽略时分秒的差
代码很简单,这边直接贴上代码:
package com.example.demo.date;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTodo2 {
public static void main(String[] args) {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate= format.parse("2007-12-24 0:30:00");
Date endDate= format.parse("2007-12-26 12:30:00");
System.out.println(beginDate);
System.out.println(endDate);
long day = (endDate.getTime() - beginDate.getTime())/(24*60*60*1000);
System.out.println("相隔的天数="+day);
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行结果:
加入时的计算
代码:
package com.example.demo.date;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
public class DateTodo2 {
public static void main(String[] args) {
try {
// 两个日期相减
String s1 = "2009-02-03 06:00:00";
String s2 = "2009-02-06 18:30:00";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
double hour = (format.parse(s2).getTime() - format.parse(s1).getTime()) / 60000;
double day = hour/(60*24*1.0);
System.out.println(day);
// 表明四舍五入,保留1位小数
BigDecimal b = new BigDecimal(day);
float f1 = b.setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
System.out.println(f1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2009-02-03 06:00:00和2009-02-06 18:30:00相差3.5天,运行结果: