闲来无聊,看几个和Java.time有关的类.
在几个月以前,我还记得以前学java的时候的教诲,当需要写一个小时的秒数的时候,不要写int seconds = 3600;,而是要int seconds = 1 * 60 * 60;因为这样可以更加清楚的表达一个小时的秒数这个概念,殊不知,早已经不用这么做了.
在1.5之后的版本中,java.util.concurrent包中提供了TimeUnit这个类,可以方便的进行时间的转换.
它是一个枚举类,包含天,小时,分钟,秒,毫秒,微秒,纳秒等几个实例,且每个实例都有转换到其他实例的方法.使用示例如下.
public static void main(String [] args) throws InterruptedException {
//2小时的秒数
System.out.println(TimeUnit.HOURS.toSeconds(2));
// 25小时的天数
System.out.println(TimeUnit.HOURS.toDays(25));
// 2秒的毫秒数
System.out.println(TimeUnit.SECONDS.toMillis(2));
}要用基于日期的值(年、月、日)来定义大量的时间,使用周期类。周期类提供了各种 get 方法, 例如 getMonths, getDays 和 getYears,这样您就可以从周期中提取出时间的数量。
如果想获得这段时间的某个时间单元的总数,可以使用ChronoUnit.between().
使用示例如下:(假设你的生日为1990年2月3号,我们来计算这个人的年龄)
public static void testPeriod() {
LocalDate now = LocalDate.now();
LocalDate birthday = LocalDate.of(1990, 2, 2);
Period p = Period.between(birthday, now);
long x = ChronoUnit.DAYS.between(birthday, now);
System.out.println(String.format("%d years %d months %d days. total %d day.", p.getYears(), p.getMonths(), p.getDays(), x));
// 检查两个日期的大小,如果前面的大于后面的,返回值为true.
System.out.println(p.isNegative());
}总之,当你想要获取某个日期离现在的总天/月/年数,可以使用ChronoUnit.between(),当你想要获取某个日期离现在的日,月,年可以使用Period
Duration比较适合短时间(一天内),高精度的时间间隔计算.
public static void testDuration() {
Duration d = Duration.between(LocalDateTime.of(2019, 7, 21, 1, 1, 1), LocalDateTime.now());
// 总小时数量
System.out.println(d.toHours());
// 总毫秒数
System.out.println(d.toMillis());
// 是否前面的时间大于后面的时间
System.out.println(d.isNegative());
}