使用Java获取当前Calendar对象的快捷方法

时间:2015-05-04 19:05:03

标签: java time calendar

给定一种方法,需要在每次调用时使用当前日/月/年的值,并且每秒调用几次(数百万次或更多次),除了创建之外,还有更快的方法来实现该功能吗?每个调用的当前时间的Calendar对象?

使用Calendar.getInstance()calendar.setTime()(使用时间字段重新计算)每秒执行多次是非常昂贵的。

标准Java解决方案更可取(例如,过度使用第三方库)。

3 个答案:

答案 0 :(得分:5)

To get the current date/time, I find that LocalDate.now() is faster than Calendar.getInstance(). The LocalDate class can be found in the java.time package, which is new since Java 8 (Of course, if you want to maintain compatibility with old Java versions, that may not be an option).

答案 1 :(得分:3)

The best solution within the scope of standard java (no 3rd party-libraries) is using the class LocalDate. So far this answer is identical to that of @Chronio, but I differ in use. The factory method now() cannot be so quick because it exploits the system timezone - maybe even using a synchronized approach anywhere in the depth of TimeZone.getDefault().

But the class LocalDate is very quick if you use its factory methods with arguments of year, month and day-of-month. Here you are just setting the state members without any timezone calculation and without any calculation of gregorian calendar math (okay only quick year-dependent length-of-month-check is involved). Just see the source code.

答案 2 :(得分:1)

use the Date, instead of Calendar class it will give you the current date