Java Date and Time: Comprehensive Management with java.time

Discover how Java's java.time package provides comprehensive handling of date and time with a variety of classes tailored for different management aspects. Learn about LocalDate for handling dates (format: yyyy-MM-dd), LocalTime for managing time (format: HH:mm:ss:ns), and LocalDateTime for combining both date and time (format: yyyy-MM-dd-HH:mm:ss:ns). Additionally, explore DateTimeFormatter, a powerful utility for formatting and parsing date-time objects seamlessly. Enhance your Java applications with these robust date and time features.



Java Date and Time

Java provides robust date and time handling through the java.time package, offering various classes for different aspects of date and time management:

  • LocalDate: Represents a date (year, month, day - yyyy-MM-dd).
  • LocalTime: Represents a time (hour, minute, second, and nanoseconds - HH:mm:ss:ns).
  • LocalDateTime: Represents both date and time (yyyy-MM-dd-HH:mm:ss:ns).
  • DateTimeFormatter: Allows formatting and parsing of date-time objects.

Display Current Date

Syntax

import java.time.LocalDate; // import the LocalDate class

public class Main {
public static void main(String[] args) {
LocalDate myObj = LocalDate.now(); // Create a date object
System.out.println(myObj); // Display the current date
}
}
Output

2024-07-04

Display Current Time

Syntax

import java.time.LocalTime; // import the LocalTime class

public class Main {
public static void main(String[] args) {
LocalTime myObj = LocalTime.now();
System.out.println(myObj);
}
}
Output

17:47:39.601467

Display Current Date and Time

Syntax

import java.time.LocalDateTime; // import the LocalDateTime class

public class Main {
public static void main(String[] args) {
LocalDateTime myObj = LocalDateTime.now();
System.out.println(myObj);
}
}
Output

2024-07-04T17:47:39.601382

Formatting Date and Time

Syntax

import java.time.LocalDateTime; // Import the LocalDateTime class
import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class

public class Main {
public static void main(String[] args) {
LocalDateTime myDateObj = LocalDateTime.now();
System.out.println("Before formatting: " + myDateObj);
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

String formattedDate = myDateObj.format(myFormatObj);
System.out.println("After formatting: " + formattedDate);
}
}
Output

Before formatting: 2024-07-04T17:47:39.601150
After formatting: 04-07-2024 17:47:39