java java中如何计算秒数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36323569/
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
how to count the seconds in java?
提问by chank062
I'm trying to understand how I could go about keeping track of the seconds that an object has been created for.
我试图了解如何跟踪创建对象的秒数。
The program I'm working on with simulates a grocery store.
我正在使用的程序模拟了一家杂货店。
Some of the foods posses the trait to spoil after a set amount of time and this is all done in a subclass of an item
class called groceryItem
. The seconds do not need to be printed but are kept track of using a currentTime
field and I don't quite understand how to count the seconds exactly.
一些食物具有在一定时间后变质的特性,这一切都在item
名为的类的子类中完成groceryItem
。不需要打印秒数,但会跟踪使用currentTime
字段,我不太明白如何准确计算秒数。
I was looking at using the Java.util.Timer or the Java.util.Date library maybe but I don't fully understand how to use them for my issue.
我正在考虑使用 Java.util.Timer 或 Java.util.Date 库,但我不完全了解如何将它们用于我的问题。
I don't really have a very good understanding of java but any help would be appreciated.
我对java并不是很了解,但任何帮助将不胜感激。
回答by Andreas
You can use either long
values with milliseconds since epoch, or java.util.Date
objects (which internally uses long
values with milliseconds since epoch, but are easier to display/debug).
您可以使用long
自纪元以来的毫秒值或java.util.Date
对象(内部使用long
自纪元以来的毫秒值,但更易于显示/调试)。
// Using millis
class MyObj {
private final long createdMillis = System.currentTimeMillis();
public int getAgeInSeconds() {
long nowMillis = System.currentTimeMillis();
return (int)((nowMillis - this.createdMillis) / 1000);
}
}
// Using Date
class MyObj {
private final Date createdDate = new java.util.Date();
public int getAgeInSeconds() {
java.util.Date now = new java.util.Date();
return (int)((now.getTime() - this.createdDate.getTime()) / 1000);
}
}
回答by Romain Hippeau
When you create your object call.
创建对象时调用。
Date startDate = new Date();
After you are done call;
打完电话后;
Date endDate = new Date();
The number of seconds elapsed is:
经过的秒数是:
int numSeconds = (int)((endDate.getTime() - startDate.getTime()) / 1000);