新日期& Java 8中的时间API [英] New Date & Time API in Java 8

查看:174
本文介绍了新日期& Java 8中的时间API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

页面上,我阅读了以下内容:

On this page i read the following:

要使用日期进行计算,这也很容易。可能是与目前的Java& 1.8:

To do calculations with dates, it is also very easy. Probably the best improvement compared to the current situation with Java < 1.8:

Period p = Period.of(2, HOURS);
LocalTime time = LocalTime.now();
LocalTime newTime = time.plus(p); // or time.plus(5, HOURS); or time.plusHours(5); 

我不清楚看到版本之前的优势, 1.8。

I don't clearly see the advantage prior to Versions < 1.8.

也许有人可以给我一个例子?
Atm我问自己,在哪里改进新的日期&时间API来自。

Maybe someone can give me an example? Atm i am asking myself, where the improvement of the new date & time API comes from.

推荐答案

使用Java< 8,你需要写一些类似的东西:

With Java < 8, you would need to write something like:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 2);

vs。与Java 8:

vs. with Java 8:

LocalTime now = LocalTime.now();
LocalTime later = now.plus(2, HOURS);

改进基本上在


  • 可读性:


    • Calendar.getInstance()命名不是很好:在没有阅读Javadoc的情况下,很难说出你所获得的实例。 LocalTime.now()是非常自我描述的:你得到一个时间,现在是

    • 要抵消日期,您调用一个抵消方法(),而使用Calendar API,您必须手动更改对象的字段(在本例中为小时)这是容易出错的。

    • readability:
      • Calendar.getInstance() is not very well named: it is hard to tell which instance you are getting without reading the Javadoc. LocalTime.now() is quite self-describing: you get a time and it is now.
      • To offset a date, you call an offsetting method (plus) whereas with the Calendar API, you have to manually change the fields of the object (in this example, the hour) which is error prone.

      • 日历API是复杂的使用,因为它混合概念,如一个简单的日期(2015年6月26日)和即时(2015年6月26日上午10点,UTC) - 前一个概念没有一个类

      • 新的Time API在各种日期/时间概念

      • the Calendar API is complicated to use because it mixes concepts, such as a simple date (June 26th 2015) and an instant in time (June 26th 2015 at 10am UTC) - there isn't a class for the former concept
      • The new Time API has a clear separation between the various date/time concepts

      • Calendar API不是afe:没有什么可以阻止你写 cal.set(123,2)这将抛出一个不太有用的 ArrayOutOfBoundsException 。新的API使用了解决这个问题的枚举。

      • 新的API使用不可变对象,这使得线程安全。

      • The Calendar API is not safe: nothing prevents you from writing cal.set(123, 2) which would throw a not-so-helpful ArrayOutOfBoundsException. The new API uses enums which solves that problem.
      • The new API uses immutable objects, which makes it thread safe.

      总的来说,新的API从jodatime中得到很大的启发,Jodatime现在已经是Java Date API的首选。您也可以阅读 Java(< 1.8)日期与JodaTime 的详细比较(大部分应用于Java 8 Date API)。

      Overall, the new API is significantly inspired from jodatime which has been the preferred Java Date API for quite some time now. You can also read this detailed comparison of Java (<1.8) date vs. JodaTime (most of it should apply to the Java 8 Date API).

      这篇关于新日期&amp; Java 8中的时间API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆