Java获取当前时间并格式化为:yyyy-MM-dd hh:mm:ss

 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());
    }

 

LocalDateTime Date区别? LocalDateTime和Date

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值