LocalDateTime是线程安全的:
LocalDateTime dateTime = LocalDateTime.now();
String str = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));
System.out.println(str);
LocalDateTime类是final类型的,不可继承的
public final class LocalDateTime
implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable
获取时间的方法now()是static静态的, 获取时间的变量是final类型的,意味着获取当前时间后不可更改。
public static LocalDateTime now() {
return now(Clock.systemDefaultZone());
}
public static LocalDateTime now(Clock clock) {
Objects.requireNonNull(clock, "clock");
final Instant now = clock.instant(); // called once
ZoneOffset offset = clock.getZone().getRules().getOffset(now);
return ofEpochSecond(now.getEpochSecond(), now.getNano(), offset);
}
LocalDateTime 是JDK1.8 开始有的。
JDK1.8 之前的有SimpleDateFormat,但是SimpleDateFormat是线程不安全的,
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = format.format(new Date());
public Date() {
this(System.currentTimeMillis());
}