温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java8中有哪些常用的时间api

发布时间:2021-06-12 18:55:27 来源:亿速云 阅读:133 作者:Leah 栏目:编程语言

这篇文章给大家介绍Java8中有哪些常用的时间api,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

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

关于Java8中有哪些常用的时间api就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI