黑马程序员技术交流社区
标题:
【上海校区】Java 8 常用时间 api
[打印本页]
作者:
不二晨
时间:
2018-11-9 09:34
标题:
【上海校区】Java 8 常用时间 api
Java 8 提供了一套新的时间 api ,比之前的 Calendar 类要简单明了很多。常用的有三个类 Instant、LocalDate 、LocalDateTime , Instant 是用来表示时刻的,类似 Unix 的时间,表示从
协调世界时
1970年1月1日0时0分0秒起至现在的总秒数,也可以获取毫秒。LocalDate 表示一个日期,只有年月日,没有时分秒。LocalDateTime 就是年月日时分秒了。
Instant
public static void main(String[] args) { Instant now = Instant.now(); System.out.println("Now secoonds:" + now.getEpochSecond()); System.out.println("Now milli :" + now.toEpochMilli());}复制代码输出当前时刻距离 1970年1月1日0时0分0秒 的秒和毫秒
Now secoonds:1541321299
Now milli :1541321299037
LocalDateTime
为了方便输出时间格式,Java8 提供了 DateTimeFormatter 类来替代之前的 SimpleDateFormat。
public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime now = LocalDateTime.now(); System.out.println("Now: " + now.format(formatter));}复制代码Now: 2018-11-04 16:53:09
LocalDateTime 提供了很多时间计算的方法,比如 加一个小时,减去一周,加上一天等等这样的计算,比之前的 Calendar 要方便许多。
public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime now = LocalDateTime.now(); System.out.println("Now: " + now.format(formatter)); LocalDateTime nowPlusDay = now.plusDays(1); System.out.println("Now + 1 day: " + nowPlusDay.format(formatter)); LocalDateTime nowMinusHours = now.minusHours(5); System.out.println("Now - 5 hours: " + nowMinusHours.format(formatter));}复制代码Now: 2018-11-04 17:02:53
Now + 1 day: 2018-11-05 17:02:53
Now - 5 hours: 2018-11-04 12:02:53
LocalDateTime 还有 isAfter 、 isBefore 和 isEqual 方法可以用来比较两个时间。LocalDate 的用法和 LocalDateTime 是类似的。
Instant 和 LocalDateTime 的互相转换
这俩的互相转换都要涉及到一个时区的问题。LocalDateTime 用的是系统默认时区。我们可以先把 LocalDateTime 转为 ZonedDateTime ,然后再转成 Instant。
public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime now = LocalDateTime.now(); System.out.println("Now: " + now.format(formatter)); Instant nowInstant = now.atZone(ZoneId.systemDefault()).toInstant(); System.out.println("Now mini seconds: " + nowInstant.toEpochMilli());}复制代码Now: 2018-11-04 17:19:16
Now mini seconds: 1541323156101
public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); Instant now = Instant.now(); System.out.println("Now mini seconds: " + now.toEpochMilli()); LocalDateTime nowDateTime = LocalDateTime.ofInstant(now, ZoneId.systemDefault()); System.out.println("Zone id: " + ZoneId.systemDefault().toString()); System.out.println("Now: " + nowDateTime.format(formatter));}复制代码Now mini seconds: 1541323844781
Zone id: Asia/Shanghai
Now: 2018-11-04 17:30:44
【转载】
作者:Simeone_xu
链接:
https://juejin.im/post/5bdebd3ee51d4576452d224f
作者:
不二晨
时间:
2018-11-14 15:18
~(。≧3≦)ノ⌒☆
作者:
魔都黑马少年梦
时间:
2018-11-15 16:28
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2