Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the date of an object in Java.

Tags:

java

oop

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

like image 851
Mayank Sharma Avatar asked May 11 '15 06:05

Mayank Sharma


People also ask

Is date an object in Java?

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT. Parameters: date - the milliseconds since January 1, 1970, 00:00:00 GMT.

What does new date () return in Java?

out. print(new Date()); I know that whatever is in the argument is converted to a string, the end value that is, new Date() returns a reference to a Date object.

How is date represented in Java?

The LocalDate represents a date in ISO format (yyyy-MM-dd) without time. We can use it to store dates like birthdays and paydays. An instance of current date can be created from the system clock: LocalDate localDate = LocalDate.


2 Answers

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;
    }
}
like image 52
Eran Avatar answered Oct 12 '22 08:10

Eran


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
    }
}
like image 29
Steve Chaloner Avatar answered Oct 12 '22 08:10

Steve Chaloner