Java:计算两个时间的相差时间

Java中通过Date、Calendar、Instant等类来表示时间。其中,Date和Calendar都是Java早期就有的时间类,Instant是在Java 8中引入的时间类。Date类的时间表示粒度为毫秒,Calendar类支持更多的操作,如用于日期加减、设置日期等,Instant类是一种更加专注于时间戳(timestamp)表示的类。 为了弥补Date缺陷:

Date 如果不格式化,打印出的日期可读性差;
使用 SimpleDateFormat 可以对日期时间进行格式化,但是 SimpleDateFormat 并非线性安全;
Date 对时间处理比较麻烦;
Date 这个类名的命名并不严谨。

《阿里巴巴开发手册》中明确禁用 static 关键字修饰 SimpleDateFormat 。

新增了LocalDate、LocalTime、LocalDateTime 三个类及相关新的 API 用以替代 Date 及其旧的使用方式

 Date

Calendar startDate = Calendar.getInstance();
startDate.setTimeInMillis(System.currentTimeMillis()-1000000);
Calendar endDate = Calendar.getInstance();
long timeDiff = endDate.getTimeInMillis() - startDate.getTimeInMillis();
long seconds = timeDiff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;

  Calendar

 Date startDate = new Date(System.currentTimeMillis()-1000000);
 Date endDate = new Date();
 long timeDiff = endDate.getTime() - startDate.getTime();
 long seconds = timeDiff / 1000;
 long minutes = seconds / 60;
 long hours = minutes / 60;
 long days = hours / 24;

 Instant

Instant startInstant = Instant.now().minusMillis(1000000);
Instant endInstant = Instant.now();
Duration duration = Duration.between(startInstant, endInstant);
long seconds = duration.getSeconds();
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;

LcoalDateTime 

LocalDateTime nowLocalDateTime  = LocalDateTime.now();
LocalDateTime endLocalDateTime  = LocalDateTime.now();

Duration duration = Duration.between(nowLocalDateTime , endLocalDateTime );
long days = duration.toDays();
long hours = duration.toHours();
long minutes = duration.toMinutes();
long millis = duration.toMillis();
// 纳秒数
long nanos = duration.toNanos();

 LocalDate

LocalDate startLocalDate = LocalDate.of(2020, 12, 27);
Period period = Period.between(startLocalDate, LocalDate.now());
int days = period.getDays();
int months = period.getMonths();
int years = period.getYears();
// 开发优先
long day= LocalDate.now().toEpochDay() - start.toEpochDay();

你可能感兴趣的:(Java,Java基础,java,开发语言)