求两个时间值之间相差几分钟
public static void main(String[] args) throws Exception {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime="2020-1-2 15:25:00";
Date parseCurrentTime = df.parse(currentTime);
long newCurrentTime = parseCurrentTime.getTime();
String reportTime="2020-1-2 15:10:00";
Date parseReportTime = df.parse(reportTime);
long oldReportTime = parseReportTime.getTime();
long diff=(newCurrentTime-oldReportTime)/1000/60;
System.out.println("当前系统时间为:"+newCurrentTime+"数据中的上报时间:"+oldReportTime+"两个时间差为:"+diff);
}
执行结果
获取两个日期相差的天数
public static int getDayBetweenTwoDate(String startDateStr, String endDateStr) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
int days = 0;
try {
Date startDate = simpleDateFormat.parse(startDateStr);
Date endDate = simpleDateFormat.parse(endDateStr);
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
days = ((int) (startCalendar.getTime().getTime() / 1000) - (int) (endCalendar.getTime().getTime() / 1000)) / (60 * 60 * 24);
} catch (ParseException e) {
e.printStackTrace();
}
return days;
}
获取两个日期相差的天数2种
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.parse("2020-03-10 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println("计算两个时间的差:");
LocalDateTime end = LocalDateTime.now();
Duration duration = Duration.between(now, end);
long days = duration.toDays();
long hours = duration.toHours();
long minutes = duration.toMinutes();
long millis = duration.toMillis();
long nanos = duration.toNanos();
System.out.println(now);
System.out.println(end);
System.out.println("相差天数:"+days);
System.out.println("发送短信耗时【 " + days + "天:" + hours + " 小时:" + minutes + " 分钟:" + millis + " 毫秒:" + nanos + " 纳秒】");
LocalDate localDate1 = LocalDate.of(now.getYear(),now.getMonthValue(),now.getDayOfMonth());
LocalDate localDate2 = LocalDate.of(end.getYear(),end.getMonthValue(),end.getDayOfMonth());
long day=localDate2.toEpochDay()-localDate1.toEpochDay();
System.out.println("相差了的天数:"+day);
}