allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œA journey of a thousand miles begins with a single step.โ€
[Lao Tzu (circa 6th century BC) โ€“ Ancient Chinese philosopher and founder of Taoism]


LocalDateTime


18.1.1 Why DateTime Matters

Dates and times are everywhere in real-world apps:

  • User sign-up dates

  • Order timestamps

  • Booking systems

  • Log files, audit trails, reports

Before Java 8, the old Date and Calendar APIs were confusing and error-prone.
Java 8 introduced java.time โ€” a modern, safe, and clear date-time framework.


โœ… Key idea:
LocalDateTime is an immutable class that combines date + time but no timezone.
For example: 2025-07-03T15:30:00.

Use LocalDateTime when you need:

  • A precise timestamp

  • No need for timezone math

  • A safe, predictable date-time representation


18.1.2 Creating LocalDateTime

You can create a LocalDateTime in multiple ways:

  • The current moment

  • A specific date-time

  • From strings or other time objects


Mini Lab: Basic LocalDateTime

java
import java.time.LocalDateTime; public class LocalDateTimeMiniLab { public static void main(String[] args) { // Current date-time LocalDateTime now = LocalDateTime.now(); System.out.println("Now: " + now); // Specific date-time LocalDateTime birthday = LocalDateTime.of(1990, 5, 15, 10, 30); System.out.println("Birthday: " + birthday); // Add days, subtract hours LocalDateTime nextWeek = now.plusDays(7); LocalDateTime yesterday = now.minusHours(24); System.out.println("Next week: " + nextWeek); System.out.println("Yesterday: " + yesterday); } }

Key points:

  • now() returns the current system date-time.

  • of() builds a specific one.

  • plusDays(), minusHours() create new modified copies โ€” original stays unchanged.