包所在位置 java.time
LocalDate:不包含具体时间的日期。
LocalTime:不含日期的时间。
LocalDateTime:包含了日期及时间。
创建时间对象(因为是静态方法不能创建对象)
LocalDateTime localDateTime=LocalDateTime.now();
线程安全的时间日期:
DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern(“yyyy-MM-dd HH-mm-ss”);
创建时间线程安全的时间日期对象:
DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern(“yyyy-MM-dd HH-mm-ss”);
String times=dateTimeFormatter.format(localDateTime);
public static void main(String[] args){
//jdk8版本的时间
LocalDateTime localDateTime=LocalDateTime.now();
System.out.println(localDateTime);
System.out.println("现在年份"+localDateTime.getYear());
System.out.println("现在月份"+localDateTime.getMonth());
System.out.println("现在月份(数字)"+localDateTime.getMonthValue());
System.out.println("现在小时"+localDateTime.getHour());
System.out.println("现在是当年的第几天"+localDateTime.getDayOfYear());
System.out.println("现在是当月的几号"+localDateTime.getDayOfMonth());
System.out.println("现在是星期几"+localDateTime.getDayOfWeek());
System.out.println("===========================================================");
//加减年份,月份 比较日期前后
LocalDateTime changedate=localDateTime.plusYears(1);
System.out.println("加后的年份"+changedate.getYear());
LocalDateTime changemonth=changedate.withMonth(5);
System.out.println("修改后的月份"+changemonth.getMonthValue());
System.out.println("添加后的日期是否在之前日期之后"+changedate.isAfter(localDateTime));
System.out.println("===========================================================");
//时间格式设置
DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");
String times=dateTimeFormatter.format(localDateTime);
System.out.println("线程安全的日期与时间"+times);
//自定义时间
LocalDateTime changeday=LocalDateTime.of(2023,10,1,5,15,30);
System.out.println("自定义时间"+changeday);
System.out.println("===========================================================");
//两时间比较
Duration duration=Duration.between(localDateTime,changeday);
System.out.println("相差的天数"+duration.toDays());
System.out.println("相差的小时"+duration.toHours());
System.out.println("相差的分钟"+duration.toMinutes());
System.out.println("相差的毫秒"+duration.toMillis());
System.out.println("相差的纳秒"+duration.toNanos());
}
效果截图: