How to find the date of an object in Java.

Suppose I have the class names "Test" and I instantiate this class. Can I find out the creation date of this instance?

+6
source share
3 answers

You will have to take care of this yourself by adding a member of the Date instance to 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; } } 
+6
source

No, objects do not have implicit timestamps. If you need to know, 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 } } 
+5
source

Avoid java.util.Date

Two other answers are correct, except that the java.util.Date class is deprecated from the new java.time ( Tutorial ) package in Java 8. The old java.util.Date/.Calendar classes are known to be unpleasant, confusing, and erroneous . Avoid them.

java.time

Get the current moment in java.time.

 ZonedDateTime instantiated = ZonedDateTime.now(); 

UTC

As a rule, it’s better to get used to doing your internal work (business logic, database, storage) in the UTC time zone. The code above implicitly refers to the current default time zone of the JVM.

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

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

Source: https://habr.com/ru/post/986946/


All Articles