What is java.util.Date Class?
import java.util.Date;
What are the java.util.Date constructors?
The java.util.Date class primarily has two constructors as described below.Date()
The first java.util.Date constructor is Date(). It initializes the object with the current date and time.
Date date = new Date();
Here, we initialize a date variable of type Date with current data and time.
import java.util.Date;
public class Example {
public static void main(String[] args) {
Date date = new Date();
System.out.println(date);
}
}
Output
Mon Dec 13 16:41:37 GMT 2021
Date(long milliseconds)
This java.util.Date constructor creates a date object the equals the number of milliseconds that have elapsed since January 1, 1970, 00:00:00 GMT.
long ms = System.currentTimeMillis();
Date date = new Date(ms);
Here, we have initialized the date variable with the current date and time only after getting the exact milliseconds passed till now through System.currentTimeMillis(); and passing as an argument to the constructor.
import java.util.Date;
public class Example1 {
public static void main(String[] args) {
long ms = System.currentTimeMillis();
Date date = new Date(ms);
System.out.println(date);
}
}
Output
Mon Dec 13 16:49:51 GMT 2021
What are the java.util.Date methods
Following are the important java.util.Date methods.boolean after(Date date): returns true if this date is after the date that is passed as an argument.
boolean before(Date date): returns true if this date is before the date that is passed as an argument.
int compareTo(Date date): compares given date with the current date.
boolean equals(Date date): compares equality between current and given date. Returns true if they are the same.
long getTime(): returns the time that this date object represents.
void setTime(long time): changes the current time to the given time.
String toString(): converts this date into a String type object.
java.util.Date Example
import java.util.Date;
public class Example2 {
public static void main(String args[]) {
long ms = 900000000;
Date date1 = new Date(ms);
System.out.println("date1 : " + date1);
Date date2 = new Date();
System.out.println("date2 : " + date2);
boolean after = date2.after(date1);
System.out.println("Is date2 after date1 : " + after);
boolean before = date2.before(date1);
System.out.println("Is date2 before date1 : " + before);
}
}
Output
date1 : Sun Jan 11 15:00:00 PKT 1970
date2 : Tue Jan 04 18:01:45 PKT 2022
Is date2 after date1 : true
Is date2 before date1 : false
GO TO FULL VERSION