Java Date and Time
Java provides extensive support for date and time manipulation through classes in the java.time
package (introduced in Java 8) and the older java.util.Date
and java.util.Calendar
classes.
1. The java.time
Package
The java.time
package offers a modern and comprehensive API for date and time.
1.1 Getting the Current Date and Time
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
public class DateTimeExample {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
System.out.println("Date: " + date);
System.out.println("Time: " + time);
System.out.println("DateTime: " + dateTime);
}
}
1.2 Formatting Date and Time
import java.time.format.DateTimeFormatter;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formattedDateTime = dateTime.format(formatter);
System.out.println("Formatted DateTime: " + formattedDateTime);
2. The java.util.Date
Class
The Date
class represents a specific instant in time, with millisecond precision.
Example: Getting Current Date
import java.util.Date;
public class OldDateExample {
public static void main(String[] args) {
Date date = new Date();
System.out.println("Current Date: " + date);
}
}
3. Key Takeaways
- Prefer the
java.time
package for modern date and time manipulation. - Use
LocalDate
,LocalTime
, andLocalDateTime
for date and time without time zones. - Use
DateTimeFormatter
for custom formatting. - Avoid using the outdated
java.util.Date
andjava.util.Calendar
classes.