Reputation: 203
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
Reputation: 338266
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.
Get the current moment in java.time.
ZonedDateTime instantiated = ZonedDateTime.now();
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
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
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