Java Date and Time
Java provides built-in classes to work with dates and time. The Java Date and Time API allows developers to create, format, compare, and manipulate dates and times easily.
In modern Java applications, the java.time package is commonly used for handling date and time because it provides simple and powerful classes.
What is Date and Time in Java?
Date and Time in Java represent information about a specific date, time, or both date and time together. Java provides different classes to store and manage these values.
The Java Date and Time API was introduced in Java 8 to replace the older Date and Calendar classes.
Java Date and Time Package
Java provides the following package to work with dates and times:
import java.time.*;
Java Date and Time Classes
The java.time package contains several useful classes for handling different date and time requirements.
LocalDate
Used to represent a date without time information.
LocalTime
Used to represent time without date information.
LocalDateTime
Used to represent both date and time together.
DateTimeFormatter
Used to format dates and times into different patterns.
Getting Current Date in Java
The LocalDate.now() method is used to get the current date.
import java.time.LocalDate;
public class Main{
public static void main(String[] args){
LocalDate today = LocalDate.now();
System.out.println(today);
}
}
Getting Current Time in Java
The LocalTime.now() method is used to get the current time.
import java.time.LocalTime;
public class Main{
public static void main(String[] args){
LocalTime time = LocalTime.now();
System.out.println(time);
}
}
Getting Current Date and Time
The LocalDateTime class is used when we need both date and time together.
import java.time.LocalDateTime;
public class Main{
public static void main(String[] args){
ocalDateTime now = LocalDateTime.now();
System.out.println(now);
}
}
Formatting Date and Time in Java
Java provides the DateTimeFormatter class to display dates and times in a custom format.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main{
public static void main(String[] args){
LocalDateTime date =
LocalDateTime.now();
DateTimeFormatter format =
DateTimeFormatter.ofPattern ("dd-MM-yyyy HH:mm");
System.out.println(date.format(format));
}
}
Why Use Java Date and Time API?
- Easy handling of dates and times.
- Provides better accuracy and performance.
- Supports date formatting and conversion.
- Avoids problems of old Date and Calendar classes.
Java Date and Time Best Practices
Use java.time
Prefer modern Java Time API instead of old date classes.
Format Properly
Use DateTimeFormatter for readable date formats.
Immutable Objects
Java date and time objects are safe and immutable.