JAVA 中操作时间的类
- JDK 8 之前
- java.util.Date
- java.util.Calendar
- JDK 8 之后
- java.time.LocalTime
- java.time.LocalDateTime
- java.time.Instant
JDK 8 之前获取时间
Date date = new Date();
System.out.println(date);
Calendar calendar = Calendar.getInstance();
Date time = calendar.getTime();
System.out.println(time);
JDK 8 之前获取时间戳
Date date = new Date();
long time = date.getTime();
System.out.println(time);
Date calendar = Calendar.getInstance().getTime();
System.out.println(calendar.getTime());
JDK8 之前格式化时间
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sf.format(new Date()));
JD8 之后
- LocalDate 只包含日期,不包含时间,不可变类,且线程安全。
- LocalTime 只包含时间,不包含日期,不可变类,且线程安全。
- LocalDateTime 既包含了时间又包含了日期,不可变类,且线程安全
JDK8之后获取时间
LocalDate localDate = LocalDate.now();
System.out.println(localDate);
LocalTime localTime = LocalTime.now();
System.out.println(localTime);
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);
JDK 8 之后获取时间戳
long milli = Instant.now().toEpochMilli();
long second = Instant.now().getEpochSecond();
System.out.println(milli);
System.out.println(second);
JDK 8 之后时间格式化
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String timeFormat = dateTimeFormatter.format(LocalDateTime.now());
System.out.println(timeFormat);
String timeFormat2 = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(timeFormat2);
JDK8 之后时间转换
String dateStr = "2021-05-09 11:19:50";
LocalDateTime localDateTime = LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(localDateTime);
Springboot 项目 中如何去除 localDateTime 中带T
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime createTime;