Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
3. Core APIs & I/O
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

23. Dates, Times, and Formatting

Handling timezones, durations, and modern LocalDates.

Java Programming: From Zero to Enterprise
3. Core APIs & I/O
February 22, 2026
63
A

[!NOTE] Historically, working with Dates in Java was notoriously awful. The original java.util.Date class was confusing, mutable, and lacked basic timezone support.

In Java 8, Oracle completely overhauled the system and introduced the java.time package, standardizing how dates should be computed.

The Big Three Classes

  1. LocalDate

Represents a date (Year, Month, Day) with no time and no timezone. Perfect for birthdays or national holidays.

import java.time.LocalDate;

public class Main {
  public static void main(String[] args) {
    LocalDate today = LocalDate.now(); 
    System.out.println(today); // Output: 2024-05-14
    
    // You can also create specific dates!
    LocalDate releaseDate = LocalDate.of(1995, 5, 23);
  }
}

  1. LocalTime

Represents a time (Hour, Minute, Second, Nanosecond) with no date. Perfect for "Opening Store Hours".

import java.time.LocalTime;

public class Main {
  public static void main(String[] args) {
    LocalTime rightNow = LocalTime.now(); 
    System.out.println(rightNow); // Output: 14:35:10.827364
  }
}

  1. LocalDateTime

A combination of both. Still essentially "floating" in space, completely untethered to a timezone. This is effectively "The time that is physically reading on your wristwatch".

import java.time.LocalDateTime;
LocalDateTime current = LocalDateTime.now();

Formatting Dates for Users

By default, Java prints dates in ISO-8601 format (YYYY-MM-DD). However, end users generally prefer localized strings, like 14-May-2024.

We accomplish this using the DateTimeFormatter.

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

public class Main {
  public static void main(String[] args) {
    LocalDateTime myDateObj = LocalDateTime.now();

    // The 'E' is the Day of week. 
    // The 'MMM' is the 3-letter month.
    DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("E, MMM dd yyyy HH:mm:ss");

    String formattedDate = myDateObj.format(myFormatObj);
    System.out.println("Formatted: " + formattedDate); // E.g., Tue, May 14 2024 14:30:00
  }
}

[!TIP] If you are building a global web application, NEVER store LocalDateTime in your database! Always convert the user's action into UTC using ZonedDateTime or Instant, save it to the database as UTC, and only ever convert it back to the local time when rendering the frontend UI in the browser.

Pick the Date-Time Type by Meaning

The right date-time class depends on what the value represents. A birthday is not a moment on the global timeline. A payment timestamp is. This distinction is the key to avoiding timezone bugs.

Type Choice Guide

Use caseTypeWhy
Birthday, exam dateLocalDateDate only
Store opening timeLocalTimeTime only
Appointment without timezoneLocalDateTimeDate plus time
Audit timestampInstantExact point in UTC
User-facing timezone-aware eventZonedDateTimeIncludes zone rules

Parsing and Formatting

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate examDate = LocalDate.parse("15-06-2026", formatter);
String display = examDate.format(formatter);

Common Mistakes

  • Storing future scheduled events without considering the user's timezone.
  • Using old mutable Date APIs in new code without a strong reason.
  • Formatting dates for storage instead of storing structured date-time values.
  • Confusing duration, period, date, and timestamp.

Mini Practice

Create a program that stores an exam date as LocalDate, calculates how many days are left, and prints it in dd MMM yyyy format.

Practice Lab: Exam Countdown

Use java.time for a real date calculation.

  1. Create a LocalDate for an upcoming exam.
  2. Get today's date with LocalDate.now().
  3. Calculate days remaining using ChronoUnit.DAYS.between.
  4. Format the exam date as dd MMM yyyy.
  5. Print a message like Exam on 15 Jun 2026, 17 days left.

Goal: Choose date-only types for date-only problems and format them for users.

Revision Checkpoint

  • LocalDate: Date without time.
  • LocalTime: Time without date.
  • LocalDateTime: Date and time without timezone.
  • Instant: Exact point on UTC timeline.
  • DateTimeFormatter: Parses and formats date-time text.

Before the quiz: Pick the correct type for birthday, audit timestamp, and store opening time.

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

easyJava
Quiz: Dates
10 questions5 min
Lesson 3 of 10 in 3. Core APIs & I/O
Previous in 3. Core APIs & I/O
22. The 'throw' and 'throws' keywords
Next in 3. Core APIs & I/O
24. Enumerable Data Structures
Back to Java Programming: From Zero to Enterprise
Back to moduleCategories