Mayank Sharma
Mayank Sharma

Reputation: 203

How to find the date of an object in Java.

Suppose I have a class names "Test" and I create an instance of that class, Can I know the creation date of that instance?

Upvotes: 6

Views: 2035

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338266

Avoid java.util.Date

The other two answers are correct, except that the java.util.Date class has been outmoded by the new java.time package (Tutorial) in Java 8. The old java.util.Date/.Calendar classes are notoriously troublesome, confusing, and flawed. Avoid them.

java.time

Get the current moment in java.time.

ZonedDateTime instantiated = ZonedDateTime.now();

UTC

Generally better to get in the habit of doing your back-end work (business logic, database, storage) all in UTC time zone. The code above relies implicitly on the JVM’s current default time zone.

To get the current moment in UTC in java.time.

ZonedDateTime instantiated = ZonedDateTime.now( ZoneOffset.UTC );

Upvotes: 1

Steve Chaloner
Steve Chaloner

Reputation: 8202

No, objects do not have implicit timestamps. If you need to know, then add an instance variable to your class.

public class Test {
    private final Date creationDate = new Date();

    public Date getCreationDate() {
        return creationDate; // or a copy of creation date, to be safe
    }
}

Upvotes: 5

Eran
Eran

Reputation: 393771

You'll have to take care of that yourself, by having a Date instance member in your Test class and initializing it in your constructor (or in its declaration) with the current Date.

public class Test {

    Date date = new Date ();

    public Date getCreationDate ()
    {
        return date;
    }
}

Upvotes: 6

Related Questions