JAVA 时间总结

JAVA 中操作时间的类

  • JDK 8 之前
    1. java.util.Date
    2. java.util.Calendar
  • JDK 8 之后
    1. java.time.LocalTime
    2. java.time.LocalDateTime
    3. 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()));
  • \color{rgb(255,0,0)}{在多线程下 SimpleDateFormat 是非线程安全的,因此在使用 SimpleDateFormat 时要注意这个问题。在多线 程下,如果使用不当,可能会造成结果不对或内存泄漏等问题}

JD8 之后

  1. LocalDate 只包含日期,不包含时间,不可变类,且线程安全。
  2. LocalTime 只包含时间,不包含日期,不可变类,且线程安全。
  3. 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;
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容