Java 8 Date and Time API Tutorial with Code Examples
This article introduces Java 8's new date‑time API, explains why the old java.util.Date and SimpleDateFormat were problematic, and provides eleven practical code examples that demonstrate how to obtain the current date, extract year/month/day, create specific dates, compare dates, work with time zones, and format or parse date strings.
Java 8 introduced a modern, immutable, and thread‑safe date‑time API (java.time) that replaces the mutable java.util.Date and non‑thread‑safe SimpleDateFormat classes.
Example 1 shows how to obtain today’s date using LocalDate.now() and print it.
Example 2 extracts the year, month, and day from the current date with getYear() , getMonthValue() , and getDayOfMonth() .
Example 3 creates a custom date with LocalDate.of(2018, 2, 6) .
Example 4 compares two dates using equals() to determine if they are the same.
Example 5 uses MonthDay to check whether today matches a recurring event such as a birthday.
Example 6 obtains the current time (without a date) via LocalTime.now() .
Example 7 adds three hours to the current time with plusHours(3) .
Example 8 calculates the date one week later using plus(1, ChronoUnit.WEEKS) .
Example 9 demonstrates moving one year forward or backward with plus and minus using ChronoUnit.YEARS .
Example 10 introduces the Clock class for obtaining timestamps and system‑default zone time.
Example 11 compares dates with isAfter() and isBefore() .
Example 12 shows how to convert a local date‑time to a specific time‑zone using ZoneId and ZonedDateTime .
Example 13 uses YearMonth to represent fixed‑date concepts such as credit‑card expiry and to query the number of days in a month.
Example 14 checks for a leap year with isLeapYear() .
Example 15 calculates the number of months between today and a future date using Period.between() .
Example 16 obtains the current instant (timestamp) with Instant.now() and shows conversion to epoch milliseconds.
Example 17 parses a compact ISO date string using DateTimeFormatter.BASIC_ISO_DATE .
Example 18 demonstrates formatting a LocalDateTime to a string and parsing it back to a LocalDate with custom patterns.
Architect's Tech Stack
Java backend, microservices, distributed systems, containerized programming, and more.
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.