java对比时间方法

LocalDateTime start = LocalDateTime.parse("2007-12-03T10:15:30");
LocalDateTime end = LocalDateTime.parse("2007-12-05T10:25:33");

//between的用法是end-start的时间,若start的时间大于end的时间,则所有的值是负的
Duration duration = Duration.between(start, end);

String timeString = duration.toString(); //此持续时间的字符串表示形式,使用基于ISO-8601秒*的表示形式,例如 PT8H6M12.345S
System.out.println("相差的天数="+duration.toDays());
System.out.println("相差的小时="+ duration.toHours());
System.out.println("相差的分钟="+duration.toMinutes());
System.out.println("相差的秒数="+duration.getSeconds());
System.out.println("相差的毫秒="+duration.toMillis());
System.out.println("相差的纳秒="+duration.toNanos());
System.out.println("timeString时间="+timeString);

//isNegative返回Duration实例对象是否为负 
System.out.println(Duration.between(start, end).isNegative());//false  end-start为正,所以此处返回false
System.out.println(Duration.between(end, start).isNegative());//true   start-end为负,所以此处返回true
System.out.println(Duration.between(start, start).isNegative());//false start-start为0,所以此处为false

//示例代码
LocalTime of1 = LocalTime.of(15, 29, 15);
LocalTime of = LocalTime.of(15, 8, 0);


Duration between = Duration.between(of, of1);
//对比相差多少秒
long l = between.getSeconds();
System.out.println(l);

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