java - 如何在不每次都创建对象的情况下获取Java中的当前时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13141094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:38:45  来源:igfitidea点击:

How to get current time in java without Creating an Object each time?

javacalendar

提问by anubhava

I know there are a lot os posts about how to get the current time in java. But im planning to code a getAge Method in a Persona class. The problem is, I need to get the current time each time method is called. Let's say a billion clients execute getMethod(with miliseconds, perhaps seconds of difference), a billion of objects will be created for such a simple thing. The only thing I did was create a member static in Person, so Person will share the instace. But this doesnt prevent the object creation.

我知道有很多关于如何在 Java 中获取当前时间的 os 帖子。但我计划在 Persona 类中编写 getAge 方法。问题是,每次调用方法时我都需要获取当前时间。假设有 10 亿个客户端执行 getMethod(有几毫秒,可能是几秒的差异),将为这样一个简单的事情创建 10 亿个对象。我所做的唯一一件事就是在 Person 中创建一个静态成员,因此 Person 将共享该实例。但这并不能阻止对象的创建。

public class Person{
//Some Attributes
private static Calendar now;
private Calendar birthDate;

public short getAge(){
now = Calendar.getInstance();

return  (short) (( now.getTimeInMillis() - birthDate.getTimeInMillis())/ 31536000000L;
}}

If you know some library that have this implemented without the waste of such heap size. Please tell me.

如果你知道一些库实现了这个而不浪费这样的堆大小。请告诉我。

Thanks.

谢谢。

回答by Keppil

No need to create a Calendar, you can get a longfrom the static method

无需创建 a Calendar,您可以long从静态方法中 获取 a

System.currentTimeMillis();

回答by anubhava

You can also create a Calendar instance once and keep calling:

您还可以创建一个 Calendar 实例并继续调用:

calendar.setTimeInMillis ( System.currentTimeMillis() );

to set the current time in calendar instance and use that calendar object to do any date calculation.

在日历实例中设置当前时间并使用该日历对象进行任何日期计算。

回答by Oh Chin Boon

With the time stamp obtained through optimized means, what additional processing / overheads will be required to make the obtained time stamp meaningful?

通过优化手段获得的时间戳,需要哪些额外的处理/开销才能使获得的时间戳有意义?

http://joda-time.sourceforge.net

http://joda-time.sourceforge.net

If you would like a library to work with date and time, go with Joda Time. I wouldn't bang on any work around.

如果您希望图书馆使用日期和时间,请使用 Joda Time。我不会做任何工作。

DateTime dt = new DateTime();  // current time

I suggest that if performance is a key concern / limiting issue that you run tests to ensure that any work around that you accept achieves non-functional results that outweigh code readability.

我建议,如果性能是一个关键问题/限制问题,您运行测试以确保您接受的任何解决方法都能实现超过代码可读性的非功能性结果。