Java Date Examples
Java's java.util.Date class represents a date and time. Most methods in this class is already deprecated for lack of internationalization support, or in favor of the java.util.Calendar class.
Here is how to instantiate a java.util.Date instance:
java.util.Date date = new java.util.Date();
Date() allocates a Date instance with the current time (measured to the nearest millisecond).
Or:
long now = System.currentTimeMillis(); java.util.Date date = new java.util.Date(now);
Date(long date) allocates a Date instance with the given time.
The given time specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT. In above case, the long that we assigned are result of System.currentTimeMillis() function.
We can use SimpleDateFormat to convert String Into Date.
import java.text.ParseException;
import java.util.Date;
import java.text.SimpleDateFormat;
public class UtilDateInitExample {
public static void main(String[] args) {
Date date1 = new Date();
System.out.println("date1: " + date1);
System.out.println("date1.getTime(): " + date1.getTime());
long now = System.currentTimeMillis();
Date date2 = new Date(now);
System.out.println("currentTimeMillis: " + now);
System.out.println("date2: " + date2);
System.out.println("date2.getTime(): " + date2.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
String strDate = "06-07-2019 04:07 PM";
try {
Date date = sdf.parse(strDate);
System.out.println(date);
} catch (ParseException ex) {
System.out.println("ParseException occured: " + ex.getMessage());
}
}
}
date1: Sat Jul 06 16:07:59 SGT 2019 date1.getTime(): 1562400479175 currentTimeMillis: 1562400479203 date2: Sat Jul 06 16:07:59 SGT 2019 date2.getTime(): 1562400479203 Sat Jul 06 16:07:00 SGT 2019
from() and toInstant()
java.time.Instant was introduced in Java 8 and it represents instantaneous point on the time-line. Two methods was introduced in java.util.Date to work with Instant.
- static Date from(Instant instant): Get an instance of Date from an Instant object.
- Instant toInstant(): Converts this Date object to an Instant.
import java.util.Date;
import java.time.Instant;
public class UtilDateFromToInstantExample {
public static void main(String[] args) {
Instant instant1 = Instant.now();
Date date1 = Date.from(instant1);
System.out.println("date: " + date1);
Instant instant2 = date1.toInstant();
System.out.println("instant1 equals instant2: " + instant1.equals(instant2));
long now = System.currentTimeMillis();
Date date2 = new Date(now);
System.out.println("date2: " + date2);
Instant instant3 = date2.toInstant();
System.out.println("instant3: " + instant3);
}
}
date: Sun Jul 07 11:41:56 SGT 2019 instant1 equals instant2: true date2: Sun Jul 07 11:41:56 SGT 2019 instant3: 2019-07-07T03:41:56.625Z
Please refer to Java 8 Instant Tutorial with Examples.
after() and before()
- boolean after(Date when): Tests if this Date is after the given Date.
- boolean before(Date when): Tests if this Date is before the given Date.
import java.text.ParseException;
import java.util.Date;
import java.text.SimpleDateFormat;
public class UtilDateAfterBeforeExample {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
String strDate1 = "06-07-2019 04:07 PM";
String strDate2 = "06-07-2019 10:20 AM";
try {
Date date1 = sdf.parse(strDate1);
System.out.println("date1: " + date1);
Date date2 = sdf.parse(strDate2);
System.out.println("date2: " + date2);
System.out.println("date1 after date2: " + date1.after(date2));
System.out.println("date2 after date1: " + date2.after(date1));
System.out.println("date1 before date2: " + date1.before(date2));
System.out.println("date2 before date1: " + date2.before(date1));
} catch (ParseException ex) {
System.out.println("ParseException occured: " + ex.getMessage());
}
}
}
date1: Sat Jul 06 16:07:00 SGT 2019 date2: Sat Jul 06 10:20:00 SGT 2019 date1 after date2: true date2 after date1: false date1 before date2: false date2 before date1: true
compareTo()
- int compareTo(Date anotherDate): Compares two Dates for ordering.
The function will return:
- value 0 if the given Date is equal to this Date
- value <0 if this Date is before the given Date
- value >0 if this Date is after the given Date
import java.text.ParseException;
import java.util.Date;
import java.text.SimpleDateFormat;
public class UtilDateCompareToExample {
public static void main(String[] args) {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss a");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd MMM yyyy HH:mm");
String strDate1 = "1980-04-09T03:45:00 AM";
String strDate2 = "1980-04-09T03:45:00 PM";
String strDate3 = "09 Apr 1980 15:45";
try {
Date dt1 = sdf1.parse(strDate1);
System.out.println("date1: " + dt1);
Date dt2 = sdf1.parse(strDate2);
System.out.println("date2: " + dt2);
Date dt3 = sdf2.parse(strDate3);
System.out.println("date3: " + dt3);
System.out.println("date1 compareTo date2: " + dt1.compareTo(dt2));
System.out.println("date2 compareTo date1: " + dt2.compareTo(dt1));
System.out.println("date1 compareTo date3: " + dt1.compareTo(dt3));
System.out.println("date2 compareTo date3: " + dt2.compareTo(dt3));
} catch (ParseException ex) {
System.out.println("ParseException occured: " + ex.getMessage());
}
}
}
date1: Wed Apr 09 03:45:00 SGT 1980 date2: Wed Apr 09 15:45:00 SGT 1980 date3: Wed Apr 09 15:45:00 SGT 1980 date1 compareTo date2: -1 date2 compareTo date1: 1 date1 compareTo date3: -1 date2 compareTo date3: 0
clone() and equals()
- Object clone(): Get a copy of this object
- boolean equals(Object obj): Compares two Dates for equality
import java.text.ParseException;
import java.util.Date;
import java.text.SimpleDateFormat;
public class UtilDateCloneEqualsExample {
public static void main(String[] args) {
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String strDate1 = "09/04/1980 03:25:00 PM";
String strDate2 = "1980-04-09T15:25:00";
String strDate3 = "1980-04-09T03:25:00 PM";
try {
Date date1 = sdf1.parse(strDate1);
System.out.println("date1: " + date1);
Date date2 = (Date) date1.clone();
System.out.println("date2: " + date2);
Date date3 = sdf2.parse(strDate2);
System.out.println("date3: " + date3);
// wrong parsing because date string not match with date/time format
Date date4 = sdf2.parse(strDate3);
System.out.println("date4: " + date4);
// false - different reference
System.out.println("date1 == date2: " + (date1 == date2));
// true
System.out.println("date1 equals date2: " + date1.equals(date2));
System.out.println("date1 equals date3: " + date1.equals(date3));
System.out.println("date1 equals date4: " + date1.equals(date4));
} catch (ParseException ex) {
System.out.println("ParseException occured: " + ex.getMessage());
}
}
}
date1: Wed Apr 09 15:25:00 SGT 1980 date2: Wed Apr 09 15:25:00 SGT 1980 date3: Wed Apr 09 15:25:00 SGT 1980 date4: Wed Apr 09 03:25:00 SGT 1980 date1 == date2: false date1 equals date2: true date1 equals date3: true
getTime() and setTime()
- long getTime(): Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
- void setTime(long time): Sets this Date object a number milliseconds after January 1, 1970 00:00:00 GMT that represent a point in time.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class UtilDateGetSetTimeExample {
public static void main(String[] args) {
Date date1 = new Date();
System.out.println("date1: " + date1);
System.out.println("date1.getTime(): " + date1.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String strDate = "09/04/1980 15:45:20";
Date date2;
try {
date2 = sdf.parse(strDate);
System.out.println("date2: " + date2);
} catch (ParseException ex) {
System.out.println("ParseException occured: " + ex.getMessage());
date2 = new Date();
}
long time = date2.getTime();
date1.setTime(time);
System.out.println("after setTime() date1: " + date1);
}
}
date1: Sun Jul 07 12:09:04 SGT 2019 date1.getTime(): 1562472544431 date2: Wed Apr 09 15:45:20 SGT 1980 after setTime() date1: Wed Apr 09 15:45:20 SGT 1980
toString()
If you print any object, java compiler internally invokes the toString() method on the object.
- String toString(): Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
where:
dow
: day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).mon
: month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).dd
: day of the month (01 through 31), as two decimal digits.hh
: hour of the day (00 through 23), as two decimal digits.mm
: minute within the hour (00 through 59), as two decimal digits.ss
: second within the minute (00 through 61), as two decimal digits.zzz
: time zone — and may reflect daylight saving time (example: WET, MYT, SGT, etc...). If time zone information is not available, then zzz is empty - that is, it consists of no characters at all.yyyy
: year, as four decimal digits.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class UtilDateToStringExample {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String strDate = "07/07/2019 14:16:55";
try {
Date date = sdf.parse(strDate);
System.out.println("date: " + date); // implicitely call toString()
System.out.println("date toString(): " + date.toString());
} catch (ParseException ex) {
System.out.println("ParseException occured: " + ex.getMessage());
}
}
}
date: Sun Jul 07 14:16:55 SGT 2019 date toString(): Sun Jul 07 14:16:55 SGT 2019
Since Date's toString() method has a fixed date/time display format, we can use SimpleDateFormat to control the display format.
Summary
Date is sufficient if we need only a current timestamp for our application, and doesn't need to operate on dates/times (like one year after, one week before, one hour later, etc). For dates operation, we can use java.util.Calendar which allow us to extract year, month, day, hour, minute, and second, and manipulating these field
Date is legacy class, which does not support internationalization. If you program is to be run in many countries with localization, consider to use Calendar and DateFormat which already support localization. But if you already use Java 8 and above, please consider to use or upgrade your Date/Time classes/utilities to use java.time standard library.