Java Date Class
Java Date Class
In Java, working with dates and times is an important aspect of building applications.
The Date class, which is part of the java.util package, allows developers
to represent and manipulate specific moments in time. Although it has been replaced by
newer date and time APIs in Java 8 and later, the Date class is still widely used and
essential to understand for beginners.
The Java Date class represents a specific instant in time, with millisecond precision.
It provides methods to handle dates, compare two dates, and convert them into
human-readable formats. Since it deals with milliseconds from the “epoch time”
(January 1, 1970, 00:00:00 GMT), it forms the basis for many time-related operations.
Java Date Class Methods
| Method | Description |
|---|---|
getTime() |
Returns the number of milliseconds since January 1, 1970. |
setTime(long time) |
Sets the Date object to a given time in milliseconds. |
after(Date when) |
Checks if this date is after the specified date. |
before(Date when) |
Checks if this date is before the specified date. |
equals(Object obj) |
Compares two dates for equality. |
compareTo(Date anotherDate) |
Compares two dates and returns a value based on which one is earlier or later. |
toString() |
Converts the date into a human-readable string format. |
Example
import java.util.Date;
public class DateExample {
public static void main(String[] args) {
// Create a new date object representing current time
Date currentDate = new Date();
// Print the current date
System.out.println("Current Date: " + currentDate);
// Get time in milliseconds
long timeInMillis = currentDate.getTime();
System.out.println("Time in milliseconds since epoch: " + timeInMillis);
// Create another date object
Date anotherDate = new Date(timeInMillis - 100000);
// Compare the two dates
if (currentDate.after(anotherDate)) {
System.out.println("Current date is after anotherDate");
}
}
}
—
Java Tutorials
Java Tutorial on this website:
For more information on Java, visit the official website :
- https://www.oracle.com/in/java/