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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:16:07  来源:igfitidea点击:

how to count the seconds in java?

javacountseconds

提问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 itemclass called groceryItem. The seconds do not need to be printed but are kept track of using a currentTimefield 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 longvalues with milliseconds since epoch, or java.util.Dateobjects (which internally uses longvalues 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);