Mastering LocalDateTime & DateTimeFormatter: The Golden Duo for Java Time Handling
This article explains how LocalDateTime and DateTimeFormatter work together to represent, format, parse, and manipulate date‑time values in Java, covering creation methods, component extraction, arithmetic, custom patterns, timezone conversion, common pitfalls, and practical use cases with concrete code examples.
LocalDateTime Overview
LocalDateTime is a class in the java.time package that represents a date‑time without a time‑zone. Its default string representation follows the pattern yyyy-MM-ddTHH:mm:ss.SSS. Key characteristics:
Immutable : thread‑safe and can be shared across threads.
Nanosecond precision : more precise than the legacy Date class.
Rich API : provides many convenient methods for date‑time manipulation, avoiding the cumbersome Calendar API.
Creating LocalDateTime Instances
Common creation methods:
// Current date‑time (nanosecond precision)
LocalDateTime now = LocalDateTime.now();
System.out.println(now); // e.g. 2025-10-18T15:30:45.123456789
// Specify year, month, day, hour, minute (optional second, nanosecond)
LocalDateTime morning = LocalDateTime.of(2025, 10, 18, 8, 30);
LocalDateTime noon = LocalDateTime.of(2025, 10, 18, 12, 0, 0);
LocalDateTime precise = LocalDateTime.of(2025, 10, 18, 14, 25, 30, 123456789);
// Combine LocalDate and LocalTime
LocalDate date = LocalDate.of(2025, 10, 18);
LocalTime time = LocalTime.of(16, 45);
LocalDateTime combo = LocalDateTime.of(date, time);
System.out.println(combo); // 2025-10-18T16:45Core Operations
Extracting components:
int year = ldt.getYear(); // 2025
Month month = ldt.getMonth(); // OCTOBER
int day = ldt.getDayOfMonth(); // 18
int hour = ldt.getHour(); // 15
int minute = ldt.getMinute(); // 42
int second = ldt.getSecond(); // 58
int nano = ldt.getNano(); // 0Adding or subtracting temporal amounts:
LocalDateTime base = LocalDateTime.of(2025, 10, 18, 10, 0);
LocalDateTime plusDay = base.plusDays(2); // 2025-10-20T10:00
LocalDateTime minusHour = base.minusHours(3); // 2025-10-18T07:00
LocalDateTime plusMinute = base.plusMinutes(15); // 2025-10-18T10:15
// Using a TemporalAmount for flexible adjustment
LocalDateTime plus = base.plus(Period.ofDays(3)); // 2025-10-21T10:00Adjusting specific fields:
LocalDateTime ldt = LocalDateTime.of(2025, 10, 18, 14, 35);
LocalDateTime adjusted = ldt.withYear(2025).withMonth(11).withDayOfMonth(1); // 2025-11-01T14:35
LocalDateTime adjusted2 = ldt.withHour(18); // 2025-10-18T18:35
LocalDateTime nextMonday = ldt.with(TemporalAdjusters.next(DayOfWeek.MONDAY));Comparisons and duration calculation:
LocalDateTime t1 = LocalDateTime.of(2025, 10, 18, 9, 0);
LocalDateTime t2 = LocalDateTime.of(2025, 10, 18, 10, 30);
boolean isBefore = t1.isBefore(t2); // true
boolean isAfter = t1.isAfter(t2); // false
boolean isEqual = t1.equals(t2); // false
Duration duration = Duration.between(t1, t2);
long minutes = duration.toMinutes(); // 90DateTimeFormatter: Formatting and Parsing
DateTimeFormatter (package java.time.format) formats LocalDateTime to strings and parses strings back. Important properties:
Thread‑safe – can be defined as a static constant.
Supports predefined ISO formats such as ISO_LOCAL_DATE_TIME, ISO_LOCAL_DATE, and ISO_LOCAL_TIME.
Allows custom patterns for complex formats.
Formatting examples:
LocalDateTime ldt = LocalDateTime.of(2025, 10, 18, 16, 25, 40);
String iso = ldt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); // 2025-10-18T16:25:40.000
String date = ldt.format(DateTimeFormatter.ISO_LOCAL_DATE); // 2025-10-18
String time = ldt.format(DateTimeFormatter.ISO_LOCAL_TIME); // 16:25:40.000
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(ldt.format(fmt)); // 2025-10-18 16:25:40
DateTimeFormatter fmt2 = DateTimeFormatter.ofPattern("MM月dd日 HH时mm分");
System.out.println(ldt.format(fmt2)); // 10月18日 16时25分Parsing examples:
// Standard ISO format
LocalDateTime parsed1 = LocalDateTime.parse("2025-10-18T17:30:00");
System.out.println(parsed1); // 2025-10-18T17:30
// Custom pattern
DateTimeFormatter custom = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分");
LocalDateTime parsed2 = LocalDateTime.parse("2025年10月18日 18时45分", custom);
System.out.println(parsed2); // 2025-10-18T18:45Practical Scenarios
Formatting an order timestamp for an e‑commerce system:
LocalDateTime orderTime = LocalDateTime.of(2025, 10, 18, 20, 15, 30);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss (E)");
String display = orderTime.format(fmt);
System.out.println("订单创建时间:" + display); // 订单创建时间:2025年10月18日 20:15:30 (星期六)Parsing user‑entered input:
String userInput = "2025/10/20 09:30";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm");
LocalDateTime inputTime = LocalDateTime.parse(userInput, fmt);
System.out.println("解析后的时间:" + inputTime); // 解析后的时间:2025-10-20T09:30Converting to different time zones (using ZoneId and ZonedDateTime):
LocalDateTime ldt = LocalDateTime.of(2025, 10, 18, 12, 0);
ZonedDateTime ny = ldt.atZone(ZoneId.of("America/New_York"));
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
System.out.println("纽约时间:" + ny.format(fmt)); // e.g. 纽约时间:2025-10-18 00:00:00 EDT
ZonedDateTime tokyo = ldt.atZone(ZoneId.of("Asia/Tokyo"));
System.out.println("东京时间:" + tokyo.format(fmt)); // e.g. 东京时间:2025-10-18 13:00:00 JSTPitfalls
Pattern case matters: MM for month, mm for minutes.
Use HH for 24‑hour clock and hh for 12‑hour clock.
Parsing requires the input string to match the pattern exactly; otherwise a DateTimeParseException is thrown. LocalDateTime lacks zone information; for cross‑zone logic prefer ZonedDateTime or OffsetDateTime. DateTimeFormatter is thread‑safe and can be defined as a static final constant for reuse.
Common Use Cases
Generating formatted log timestamps:
private static final DateTimeFormatter LOG_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
LocalDateTime now = LocalDateTime.now();
String ts = now.format(LOG_FORMATTER);
System.out.println("[" + ts + "] " + message);Parsing API response strings such as "dd/MM/yyyy HH:mm:ss":
String apiTime = "18/10/2025 14:20:30";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
LocalDateTime time = LocalDateTime.parse(apiTime, fmt);Calculating the interval between two moments and presenting it as hours and minutes:
LocalDateTime start = LocalDateTime.of(2025, 10, 18, 9, 0);
LocalDateTime end = LocalDateTime.of(2025, 10, 18, 18, 30);
Duration d = Duration.between(start, end);
long hours = d.toHours();
long minutes = d.toMinutes() % 60;
System.out.println("总共耗时:" + hours + "小时" + minutes + "分钟"); // 总共耗时:9小时30分钟Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
