文章目录
- Period
- 常用方法
- 代码
- During
- 常用方法
- 代码
Period
用于计算两个LocalDate对象 相差的年数,月数,天数
常用方法
代码
package NewTime;
import java.time.LocalDate;
import java.time.Period;
/**
* @Author: ggdpzhk
* @CreateTime: 2024-08-31
*/
public class Test_Period {
public static void main(String[] args) {
//传入两个日期对象的到一个 Period对象
Period p = Period.between(LocalDate.of(2024, 8, 1), LocalDate.of(2024, 8, 31));
System.out.println(p);
//获取两个日期对象相差的年、月、日
System.out.println(p.getYears());
System.out.println(p.getMonths());
System.out.println(p.getDays());
}
}
During
常用方法
代码
package NewTime;
import java.time.Duration;
import java.time.LocalDateTime;
/**
* @Author: ggdpzhk
* @CreateTime: 2024-08-31
*/
public class Test_During {
public static void main(String[] args) {
//传入两个时间对象的到Duration对象
LocalDateTime start = LocalDateTime.of(2020, 8, 31, 3, 3, 12);
LocalDateTime end = LocalDateTime.of(2020, 9,30 , 3, 3, 12);
Duration duration = Duration.between(start, end);
//计算相隔的年
Long years = duration.toDays() / 365 ;
Long days = duration.toDays() ;
Long hours = duration.toHours() ;
Long minutes = duration.toMinutes() ;
Long seconds = duration.getSeconds() ;
Long millis = duration.toMillis() ;
Long nanos = duration.toNanos() ;
System.out.println("相隔的年数:" + years);
System.out.println("相隔的天数:" + days);
}
}