In this Java tutorial, you will learn how to access the current date and time from the system, create date-time values from milliseconds, compare dates, parse date-time strings, and choose between the older java.util.Date class and the modern Java Date-Time API.
Date and Time in Java: Legacy Date and Modern java.time
Date and Time in Java can be handled in two common ways. Older Java programs often use java.util.Date to represent a timestamp. Newer Java programs, especially Java 8 and later, usually use the java.time package because it gives clearer classes for dates, times, time zones, durations, and formatting.
The existing examples in this tutorial first explain java.util.Date, because it is still seen in many codebases. After that, you will also see practical examples with LocalDate, LocalDateTime, ZonedDateTime, Instant, and DateTimeFormatter. Oracle’s official Java tutorial also documents the modern Date-Time API.
Common Java Date and Time Classes
Before writing date-time code, it helps to choose the class that matches the value you want to represent.
| Java class | Package | What it represents | Typical use |
|---|---|---|---|
Date | java.util | A point in time, stored as milliseconds from the Unix epoch | Legacy APIs and older code |
Instant | java.time | A machine timestamp on the UTC time-line | Logging, persistence, event timestamps |
LocalDate | java.time | A date without time or time zone | Birth date, invoice date, exam date |
LocalTime | java.time | A time without date or time zone | Opening time, closing time |
LocalDateTime | java.time | Date and time without time zone | Local schedule values |
ZonedDateTime | java.time | Date and time with a time zone | Meetings, travel, region-specific time |
DateTimeFormatter | java.time.format | Parser and formatter for date-time text | Converting strings to date-time values and back |
Get Current Date and Time in Java Using java.util.Date
java.util.Date stores a timestamp value. When you create a new Date object with the no-argument constructor, Java captures the current system time at that moment.
java.util.Date Example to Print Current System Time
In the following program, we print time, to be precise, the system time when executing the statement new Date().
DateTimeDemo.java
import java.util.Date;
public class DateTimeDemo {
public static void main(String[] args) {
Date date = new Date();
System.out.println(date.toString());
}
}
Output
Mon Mar 27 00:04:46 IST 2017
The exact output changes every time you run the program. It also depends on the default time zone and locale of the system where the program is executed.
Some of the methods offered by java.util.Date() class :
java.util.Date toString() Format in Java
As we have seen this method in the above program, DateTimeDemo.java, java.util.Date().toString() prints the time in the following format.
dow mon dd hh:mm:ss zzz yyyy
dow : Day Of Week
mon : Month
dd : Day of Month
hh : Hour of the day
mm : Minute of the hour
ss : Second of the minute
zzz : TimeZone
yyyy: Year
How to call java.util.Date().toString() in your program.
String dateTime = new java.util.Date().toString();
System.out.println(dateTime);
Output
Mon Mar 27 00:04:46 IST 2017
For user-facing output, prefer formatting with DateTimeFormatter in the modern API instead of relying only on Date.toString(), because toString() is not designed for custom display formats.
Create Java Date from Milliseconds Since Epoch
This constructor of java.util.Date() class, creates a new Date() object and initializes it to the time “value milliseconds” after 00:00 GMT hours, Jan 1st 1970 or 05:30 IST hours, Jan 1st 1970.
In Java date-time terminology, 00:00:00 UTC on 1 January 1970 is called the Unix epoch. The value passed to new Date(long milliseconds) is counted from that instant. The printed local time depends on the system time zone.
java.util.Date Constructor with Milliseconds Example
java.util.Date(4752) would initialize the object to 4752( = 4seconds + 752milliseconds) after 00:00 GMT hours, Jan 1st 1970 which is Thu Jan 01 00:00:04 IST 1970 or Thu Jan 01 05:30:04 IST 1970.
In the following program, we will call java.util.Date() with 4752 passed as argument.
DateTimeDemo.java
import java.util.Date;
public class DateTimeDemo {
public static void main(String[] args) {
Date date1 = new Date(4752L);
System.out.println(date1.toString());
}
}
Output
Thu Jan 01 05:30:04 IST 1970
The output above assumes the default time zone is IST. On a machine configured for UTC, the same timestamp would be printed with a UTC-based time instead.
Get Current Date and Time in Java Using java.time
For new Java code, the java.time package is usually clearer than java.util.Date. It separates date-only, time-only, date-time, and time-zone-aware values into different classes.
LocalDate, LocalTime, LocalDateTime, and ZonedDateTime Example
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZonedDateTime;
public class ModernDateTimeDemo {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
LocalTime currentTime = LocalTime.now();
LocalDateTime currentDateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = ZonedDateTime.now();
System.out.println("Current date: " + currentDate);
System.out.println("Current time: " + currentTime);
System.out.println("Current date and time: " + currentDateTime);
System.out.println("Current zoned date and time: " + zonedDateTime);
}
}
Sample output
Current date: 2024-11-06
Current time: 10:15:30.123456
Current date and time: 2024-11-06T10:15:30.123456
Current zoned date and time: 2024-11-06T10:15:30.123456+05:30[Asia/Kolkata]
Use LocalDate when only the calendar date matters. Use ZonedDateTime when the time zone is part of the meaning, such as meetings or scheduled jobs in a specific region.
Format Date and Time in Java with DateTimeFormatter
DateTimeFormatter is used to convert date-time objects into readable strings and to parse strings back into date-time objects. This is safer and clearer than manually splitting date strings.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class FormatDateTimeDemo {
public static void main(String[] args) {
LocalDateTime dateTime = LocalDateTime.of(2024, 11, 6, 10, 15, 30);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formattedDateTime = dateTime.format(formatter);
System.out.println(formattedDateTime);
}
}
Output
06-11-2024 10:15:30
Parse Date and Time String in Java
When a date-time value comes from a file, form field, API response, or database text column, you often need to parse it. The pattern in DateTimeFormatter must match the input string.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class ParseDateTimeDemo {
public static void main(String[] args) {
String input = "06-11-2024 10:15:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(input, formatter);
System.out.println(dateTime);
}
}
Output
2024-11-06T10:15:30
If the input string does not match the formatter pattern, Java throws a parsing exception. Always validate external date-time strings before using them in business logic.
Compare Dates in Java Using compareTo()
This method compares if the date is after or before or equals the specified date.
- Negative return value mean that the date is prior to the speicified date.
- Positive return value mean that the speicified date is prior to the date.
- Zero return value mean that the speicified date is same as that of the date, to milliseconds.
In simple words, date1.compareTo(date2) returns a negative value when date1 is earlier than date2, a positive value when date1 is later than date2, and zero when both represent the same millisecond.
java.util.Date compareTo() Example
In the following example, we have date1 and date2, and we shall try the below cases :
- date1.compareTo(date2);
- date2.compareTo(date1);
- date1.compareTo(date1);
DateTimeDemo.java
import java.util.Date;
public class DateTimeDemo {
public static void main(String[] args) {
Date date1 = new Date(1490554798133L);
Date date2 = new Date(1490554855875L);
System.out.println("date1 : "+date1.toString());
System.out.println("date2 : "+date2.toString());
System.out.println("\nIs date2 prior to date1 : "+date1.compareTo(date2));
System.out.println("Negative value of date1.compareTo(date2) means the date2 is not prior to date1.");
System.out.println("\nIs date1 prior to date2 : "+date2.compareTo(date1));
System.out.println("Positive value of date1.compareTo(date2) means the date2 is prior to date1.");
System.out.println("\nIs date1 same as date1 : "+date1.compareTo(new Date(date1.getTime())));
System.out.println("Zero value of date1.compareTo(new Date(date1.getTime())) means the date1 has same time as that of date1, which is by the way evident in this case");
}
}
Output
date1 : Mon Mar 27 00:29:58 IST 2017
date2 : Mon Mar 27 00:30:55 IST 2017
Is date2 prior to date1 : -1
Negative value of date1.compareTo(date2) means the date2 is not prior to date1.
Is date1 prior to date2 : 1
Positive value of date1.compareTo(date2) means the date2 is prior to date1.
Is date1 same as date1 : 0
Zero value of date1.compareTo(new Date(date1.getTime())) means the date1 has same time as that of date1, which is by the way evident in this case
The printed labels in this demo are worded around the comparison being tested. The reliable rule is the return value of compareTo(): negative means the left-side object is earlier, positive means it is later, and zero means both are equal.
Check Whether a Java Date Is After Another Date
This method checks if the Date is after the specified date. If yes, returns a true, else returns a false.
java.util.Date after() Example
The following program shows the working of method java.util.Date().after(Date date)
DateTimeDemo.java
import java.util.Date;
public class DateTimeDemo {
public static void main(String[] args) {
Date date1 = new Date(1490554798133L);
Date date2 = new Date(1490554855875L);
System.out.println("date1 : "+date1);
System.out.println("date2 : "+date2);
System.out.println();
System.out.println("Is date1 after date2 ? "+date1.after(date2));
System.out.println("Is date2 after date1 ? "+date2.after(date1));
}
}
Output
date1 : Mon Mar 27 00:29:58 IST 2017
date2 : Mon Mar 27 00:30:55 IST 2017
Is date1 after date2 ? false
Is date2 after date1 ? true
Check Whether a Java Date Is Before Another Date
This method checks if the Date is before the specified date. If yes, returns a true, else returns a false.
java.util.Date before() Example
The following program shows the working of method java.util.Date().before(Date date)
DateTimeDemo.java
import java.util.Date;
public class DateTimeDemo {
public static void main(String[] args) {
Date date1 = new Date(1490554798133L);
Date date2 = new Date(1490554855875L);
System.out.println("date1 : "+date1);
System.out.println("date2 : "+date2);
System.out.println();
System.out.println("Is date1 before date2 ? "+date1.before(date2));
System.out.println("Is date2 before date1 ? "+date2.before(date1));
}
}
Output
date1 : Mon Mar 27 00:29:58 IST 2017
date2 : Mon Mar 27 00:30:55 IST 2017
Is date1 before date2 ? true
Is date2 before date1 ? false
Check Whether Two Java Date Objects Are Equal
Returns true if the date is same as the specified date, to milliseconds. Else the method returns false.
java.util.Date equals() Example
Following is a sample program to show the working of java.util.Date().equals(Date date) method.
DateTimeDemo.java
import java.util.Date;
public class DateTimeDemo {
public static void main(String[] args) {
Date date1 = new Date(1490554798133L);
Date date2 = new Date(1490554855875L);
Date date3 = new Date(1490554798133L);
System.out.println("Is date1 equals date2 ? "+date1.equals(date2));
System.out.println("Is date1 equals date3 ? "+date1.equals(date3));
}
}
Output
Is date1 equals date2 ? false
Is date1 equals date3 ? true
Clone a java.util.Date Object in Java
The clone method creates a new object, an exact copy of the specified Date.
java.util.Date clone() Example
In the following example, we shall clone date1 to create a new date2.
DateTimeDemo.java
import java.util.Date;
public class DateTimeDemo {
public static void main(String[] args) {
Date date1 = new Date(1490554798133L);
Date date2 = (Date) date1.clone();
System.out.println("Is date1 equals date2 ? "+date1.equals(date2));
}
}
Output
Is date1 equals date2 ? true
Convert Between java.util.Date and java.time.Instant
Many projects use both old and new date-time APIs because older libraries may still return java.util.Date. You can bridge them through Instant.
import java.time.Instant;
import java.util.Date;
public class DateInstantConversionDemo {
public static void main(String[] args) {
Date oldDate = new Date();
Instant instant = oldDate.toInstant();
Date convertedBack = Date.from(instant);
System.out.println("Instant: " + instant);
System.out.println("Date: " + convertedBack);
}
}
This conversion is useful when a legacy API gives a Date, but the rest of your application works with the modern java.time classes.
Compare Modern Java Date-Time Values
The modern Java Date-Time API also supports comparison methods such as isBefore(), isAfter(), and isEqual(). These method names make date-time comparisons easier to read.
import java.time.LocalDate;
public class LocalDateCompareDemo {
public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2024, 11, 6);
LocalDate date2 = LocalDate.of(2024, 11, 10);
System.out.println(date1.isBefore(date2));
System.out.println(date2.isAfter(date1));
System.out.println(date1.isEqual(LocalDate.of(2024, 11, 6)));
}
}
Output
true
true
true
Common Mistakes with Date and Time in Java
- Using
Date.toString()for final display: It is quick for debugging, but a formatter is better for user-facing output. - Ignoring time zones: The same instant can display differently in different zones. Use
ZonedDateTimewhen the zone matters. - Using
LocalDateTimeas a global timestamp:LocalDateTimehas no time zone. UseInstantfor machine timestamps. - Parsing strings without matching the pattern: The formatter pattern must match the input text exactly.
- Mixing old and new APIs without conversion: Use
toInstant()andDate.from()when moving betweenDateandInstant.
QA Checklist for Java Date and Time Tutorial Examples
- Check whether each example clearly says if the output depends on the system date, time zone, or locale.
- Check that legacy
java.util.Dateexamples are not presented as the only recommended approach for new Java code. - Check that new date-time examples use the correct class:
LocalDatefor date-only values,Instantfor timestamps, andZonedDateTimefor zone-aware values. - Check that every new Java code block uses a PrismJS-compatible
language-javaclass and every result block usesoutput. - Check that date parsing examples include a formatter pattern that matches the input string.
FAQs on Date and Time in Java
How do I get the current date and time in Java?
In legacy code, you can use new Date(). In modern Java, use LocalDate.now() for the current date, LocalTime.now() for the current time, LocalDateTime.now() for local date and time, or ZonedDateTime.now() when the time zone matters.
Should I use java.util.Date or java.time in new Java code?
For new code, prefer the java.time package. Use java.util.Date mainly when working with older APIs or legacy code that still expects it.
What is the difference between Instant and LocalDateTime in Java?
Instant represents a timestamp on the UTC time-line, so it is suitable for storing machine time. LocalDateTime represents a date and time without a time zone, so it is suitable for local schedule values where the zone is handled separately.
Why does the same Java Date print different times on different computers?
Date stores a timestamp, but Date.toString() prints it using the system’s default time zone. If two computers use different time zones, the same timestamp can be displayed with different local times.
How do I compare two dates in Java?
With java.util.Date, use compareTo(), before(), after(), or equals(). With modern classes such as LocalDate, use readable methods like isBefore(), isAfter(), and isEqual().
Date and Time in Java: Key Takeaways
Concluding this Java Tutorial, Date and Time in Java, we have seen how to create a java.util.Date() object, get the local time from it using toString() method, compare it to an other Date, check if the date is before or after a specified date, if two dates are equal in value.
For modern Java applications, prefer java.time classes where possible. Use Instant for timestamps, LocalDate for date-only values, LocalDateTime for local date-time values, ZonedDateTime for time-zone-aware values, and DateTimeFormatter for formatting and parsing.
TutorialKart.com