Jdk8常用时间类的使用

jdk8时间类的概念

jdk8时间类的来源是因为以前的时间日期类设计的不足,所以jdk8引入了java.time包来作为新的日期时间处理类。

  • java.time包中主要包含以下类
说明
Clock 使用时区提供对当前即时,日期和时间的访问的时钟
Duration 计算两个“时间”的间隔
Instant 在时间线上的瞬间点(常用)
LocalDate 一个不可变的日期时间对象,表示日期,通常被视为年月日(常用)
LocalTime 是一个不可变的日期时间对象,代表一个时间,通常被看作是小时 - 秒 (常用)
LocalDateTime 是一个不可变的日期时间对象,代表日期时间,通常被视为年 - 月 - 日 - 时 - 分 - 秒(常用)
MonthDay 是一个不变的日期时间对象,代表一年和一个月的组合
OffsetDateTime 具有偏移量的日期时间的不可变表示
OffsetTime 是一个不可变的日期时间对象,表示一个时间,通常被视为小时 - 秒 - 秒
Period 用于计算两个“日期”的间隔
Year 代表一年的不可变日期时间对象
YearMonth 是一个不变的日期时间对象,表示一年和一个月的组合
ZonedDateTime 是具有时区的日期时间的不可变表示

Instant

  //2019-12-18T09:12:24.377Z ,我们是东八区,默认是按照本初子午线为准所以要早8个小时
  Instant instant = Instant.now();//直接获取当前时刻
  long l = instant.toEpochMilli();//类似与getTime()
  //根据时区返回ZoneDateTime
  OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));//原时间上加8个小时

LocalDate 和 DateTimeFormatter

  //显示当前时间 年-月-日
  LocalDate localDate = LocalDate.now();//2019-12-18
  //适用于LocalDateTime   FormatStyle.SHORT  FormatStyle.LONG FormatStyle.MEDIUM      FormatStyle.FULL
  DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(localDate);//19-12-18
  DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).format(localDate);//2019年12月18日 
  DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).format(localDate);//2019-12-18
  DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).format(localDate);//2019年12月18日 星期三

LocalTime

//显示时分秒
LocalTime localTime = LocalTime.now();//17:11:49.751

LocalDateTime 和 DateTimeFormatter

  //显示年月日 时分秒
  LocalDateTime localDateTime = LocalDateTime.now();//2019-12-18T17:11:49.751
  LocalDateTime a = LocalDateTime.of(2020,12,12,12,12,12);//修改时间的年月日时分秒
  //适用于LocalDateTime   FormatStyle.SHORT  FormatStyle.LONG FormatStyle.MEDIUM
  DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).format(localDateTime);//19-12-18 下午5:19
  DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).format(localDateTime);//2019年12月18日 下午05时21分24秒
  DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).format(localDateTime);//2019-12-18 17:22:26

DateTimeFormatter

  //格式化日期格式
  DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;//默认格式
  formatter.parse("2019-12-18T17:04:32.876");//ISO resolved to 2019-12-18T17:04:32.876
  //类似SimpleDateFormat 最香的自定义格式时间方式
  DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
发布了67 篇原创文章 · 获赞 19 · 访问量 9876

猜你喜欢

转载自blog.csdn.net/qq_41530004/article/details/103680232