Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count the seconds in java?

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.

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.

I don't really have a very good understanding of java but any help would be appreciated.

like image 720
chank062 Avatar asked Mar 31 '16 03:03

chank062


2 Answers

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).

// 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);
    }
}
like image 77
Andreas Avatar answered Oct 29 '22 17:10

Andreas


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);
like image 23
Romain Hippeau Avatar answered Oct 29 '22 16:10

Romain Hippeau