Skip to main content
Advertisement

10.3 Date & Time Formatting (DateTimeFormatter)

We have finished the internal date and time computations. Now comes the final gateway: "Creating human-readable date strings, or conversely, converting strings back into date objects."

For this, we use the DateTimeFormatter class.

1. Date Object → String Conversion: format()

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

LocalDateTime now = LocalDateTime.now();

// Define the desired date format pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

// Convert the LocalDateTime object into a formatted string
String formatted = now.format(formatter);
System.out.println(formatted); // 2026-03-13 17:30:08

Key Pattern Characters

PatternMeaningExample
yyyyYear (4 digits)2026
yyYear (2 digits)26
MMMonth (2 digits, 01~12)03
MMonth (1-2 digits, 1~12)3
ddDay (2 digits, 01~31)07
dDay (1-2 digits, 1~31)7
HHHour (24-hour clock, 00~23)17
hhHour (12-hour clock, 01~12)05
mmMinutes (00~59)30
ssSeconds (00~59)08
EDay of week (abbreviated)Thu
EEEEDay of week (full name)Thursday

Let's print dates in a variety of formats:

LocalDateTime now = LocalDateTime.now();

// US-style date notation
DateTimeFormatter us = DateTimeFormatter.ofPattern("MM/dd/yyyy");
System.out.println(now.format(us)); // 03/13/2026

// Standard format with day of week
DateTimeFormatter withDay = DateTimeFormatter.ofPattern("yyyy-MM-dd (EEEE)");
System.out.println(now.format(withDay)); // 2026-03-13 (Thursday)

// ISO 8601 standard format (frequently used in API communication)
DateTimeFormatter iso = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
System.out.println(now.format(iso)); // 2026-03-13T17:30:08

2. String → Date Object Conversion: parse()

Conversely, to convert a textual date string like "2026-03-13" back into a LocalDate object, use the parse() method. You will use this essentially whenever you receive dates as raw text from web forms or external APIs.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

String dateString = "03/13/2026";

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");

// Parse the string into a LocalDate object
LocalDate parsedDate = LocalDate.parse(dateString, formatter);

System.out.println("Parsed Date: " + parsedDate); // 2026-03-13
System.out.println("Year: " + parsedDate.getYear()); // 2026
System.out.println("Month: " + parsedDate.getMonthValue()); // 3
System.out.println("Day: " + parsedDate.getDayOfMonth()); // 13

With this, you have now mastered all the core skills for handling dates and times in Java!

  • LocalDate / LocalTime / LocalDateTime: Creating date/time objects
  • Period / Duration: Calculating intervals between dates/times
  • DateTimeFormatter: Bidirectional conversion between date/time objects and strings

In the next Phase, we will dive into Java's Collection Framework (List, Set, Map)!

Advertisement