Java Date and Time API
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Java Date and Time API

Harine

Java Date and Time API

Java provides a modern and robust date-time API in the java.time package (introduced in Java 8). This API replaces older date classes and offers clear, immutable, and thread-safe representations of dates and times.

Display the Current Date in Java

LocalDate represents a date without time or timezone.

import java.time.LocalDate;

public class CurrentDateExample {

  public static void main(String[] args) {

  LocalDate today = LocalDate.now();

  System.out.println("Today's date: " + today);

 }

}

Sample Output

Today's date: 2026-02-24

Display the Current Time

LocalTime represents time without date or timezone

import java.time.LocalTime;

public class CurrentTimeExample {

  public static void main(String[] args) {

    LocalTime currentTime = LocalTime.now();

    System.out.println("Current time: " + currentTime);

  }

}

Sample Output

Current time: 10:28:11.700767

The value reflects the system clock of the machine running the program.

Display Current Date and Time

LocalDateTime combines both date and time.

import java.time.LocalDateTime;

public class CurrentDateTimeExample {

  public static void main(String[] args) {

    LocalDateTime now = LocalDateTime.now();

    System.out.println("Now: " + now);

  }

}

Sample Output

Now: 2026-02-24T10:28:11.700212

The T separator follows the ISO-8601 standard between date and time.

Formatting Date and Time in Java

Raw LocalDateTime output includes the T separator and nanoseconds. To display user-friendly

formats, use DateTimeFormatter.

import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;

public class DateFormattingExample {

  public static void main(String[] args) {

    LocalDateTime timestamp = LocalDateTime.now();

    System.out.println("Default format: " + timestamp);

    DateTimeFormatter formatter =

       DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

    String formatted = timestamp.format(formatter);

    System.out.println("Formatted: " + formatted);

  }

}

Sample Output

Default format: 2026-02-24T10:28:11.700089

Formatted: 24-02-2026 10:28:11

Why Use java.time Instead of Old Date Classes?

The modern API provides major improvements over java.util.Date and Calendar:

  • Immutable and thread-safe
  • Clear separation of date/time concepts
  • ISO-8601 standard compliance
  • Powerful formatting and parsing
  • Fluent API design

Tags
Our website uses cookies to enhance your experience. Learn More
Accept !