java.util.Date class was one of Java's first date classes.
Today most of the methods in the class are deprecated in favor of the
You can still use the
java.util.Date class to represent a date though.
Here is how to instantiate a
java.util.Date date = new java.util.Date();
Date instance contains the current time as its date and time.
You can access the date and time contained in a
getTime() method, like this:
java.util.Date date = new java.util.Date(); long time = date.getTime();
You can also create a
java.util.Date from a time in milliseconds, like this:
long now = System.currentTimeMillis(); java.util.Date date = new java.util.Date(now);
You can compare
java.util.Date instance because the class implements
java.lang.Comparable interface. Here is how:
java.util.Date date1 = new java.util.Date(); java.util.Date date2 = new java.util.Date(); int comparison = date1.compareTo(date2);
The comparison follows the rules for the
Comparable interface, meaning
compareTo() method returns:
- An int larger than 0 if the date the method is called on is later than the date given as parameter.
- An int value of 0 if the dates are equal.
- An int value less than 0 if the date the method is called on is earlier than the date given as parameter.
java.util.Date also has two shortcut methods to do comparisons. These are
after() methods. Here are two examples of how
to use them:
java.util.Date date1 = new java.util.Date(); java.util.Date date2 = new java.util.Date(); boolean isBefore = date1.before(date2); boolean isAfter = date1.after (date2);
Getting the Year, Month, Day of Month, Hour etc.
The methods to get the year, month, day of month, hour etc. are deprecated. Apparently the algorithms used internally were not entirely correct.
If you need to get or set the year, month, day of month etc. use a