时间类
Date类
- ZonedDateTime: 带时区的时间
- ZoneId: 带时区
- Instant: 时间戳
日期格式化类
SimpleDateFormat
- DateTimeFormatter
Date d1 = new Date();
System.out.println(d1);
SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(smt.format(d1));
日历类
Calendar
- LocalDateTime 年月日时分秒(重点)
- LocalDate 年月日
- LocalTime 时分秒
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDate d2= LocalDate.now();
LocalDateTime d4 = LocalDateTime.now();
LocalTime t1 = LocalTime.now();
String format = LocalDateTime.now().format(
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
); // datetime转字符串
// 不会改变原始值大小,会生成一个新的日期对象
d4.getYear(); // 获取
LocalDateTime d5 = d4.withYear(2000);// 修改
System.out.println("d5:" + d5.format(formatter));
LocalDateTime d6 = d4.minusYears(2);// 减少
System.out.println("d6:"+ d6.format(formatter));
LocalDateTime d7 = d4.plusYears(2);// 增加
System.out.println("d7:" + d7.format(formatter));
工具类
- Duration :时间间隔(秒、纳秒)
- Period:时间间隔(时分秒)
- ChronoUnit:时间间隔(所有)重点
package com.lty;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class ChronoUnitDemo {
public static void main(String[] args) {
LocalDateTime today = LocalDateTime.now();
LocalDateTime birthDate = LocalDateTime.of(2000, 5, 21, 0, 0, 0, 0);
System.out.println("相差的年数: " + ChronoUnit.YEARS.between(birthDate,today));
System.out.println("相差的月数: " + ChronoUnit.MONTHS.between(birthDate,today));
System.out.println("相差的周数: " + ChronoUnit.WEEKS.between(birthDate,today));
System.out.println("相差的天数: " + ChronoUnit.DAYS.between(birthDate,today));
System.out.println("相差的时数: " + ChronoUnit.HOURS.between(birthDate, today));
System.out.println("相差的分数: " + ChronoUnit.MINUTES.between(birthDate, today));
System.out.println("相差的秒数: " + ChronoUnit.SECONDS.between(birthDate,today));
System.out.println("相差的毫秒数: " + ChronoUnit.MILLIS.between(birthDate,today));
System.out.println("相差的微秒数: " + ChronoUnit.MICROS.between(birthDate,today));
System.out.println("相差的纳秒数: " + ChronoUnit.NANOS.between(birthDate, today));
System.out.println("相差的半天数: " + ChronoUnit.HALF_DAYS.between(birthDate, today));
System.out.println("相差的十年数: " + ChronoUnit.DECADES.between(birthDate,today));
System.out.println("相差的世纪有年数: " + ChronoUnit.CENTURIES.between(birthDate,today));
System.out.println("相差的千年数: " + ChronoUnit.MILLENNIA.between(birthDate,today));
System.out.println("相差的纪元数: " + ChronoUnit.ERAS.between(birthDate,today));
}
}
标签:Java,System,birthDate,时间,println,ChronoUnit,today,out
From: https://www.cnblogs.com/his365/p/17117498.html