Working With Date and Time in Java: A Practical Tutorial

Handling dates and times is a common task in software development—and one that can quickly become tricky without the right tools. Fortunately, Java provides a powerful, modern date-time API through the java.time package, introduced in Java 8. This tutorial will walk you through the essentials of working with date and time in Java using this API, complete with examples you can use right away.


Why Use the java.time API?

Before Java 8, developers relied on java.util.Date, Calendar, or third-party libraries like Joda-Time. These older classes had several issues—lack of thread safety, confusing design, and mutable objects.

The java.time package:

  • Is easy to use
  • Is immutable and thread-safe
  • Supports time zones, locales, and formatting/parsing
  • Inspired by the popular Joda-Time library

1. Getting the Current Date and Time

Java offers different classes depending on what you need: only date, only time, or both.

Current Date

LocalDate today = LocalDate.now();
System.out.println("Today's Date: " + today);

Current Time

LocalTime timeNow = LocalTime.now();
System.out.println("Current Time: " + timeNow);

Current Date and Time

LocalDateTime current = LocalDateTime.now();
System.out.println("Current DateTime: " + current);

2. Working With Time Zones

When working with international applications, you’ll often need time-zone-aware dates.

Get current date-time in a specific zone:

ZonedDateTime zonedDt = ZonedDateTime.now(ZoneId.of("America/New_York"));
System.out.println(zonedDt);

List all available time zones

ZoneId.getAvailableZoneIds().forEach(System.out::println);

3. Formatting and Parsing Dates

The DateTimeFormatter class lets you convert dates to strings and vice-versa.

Formatting a date

LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String formatted = date.format(formatter);

System.out.println("Formatted Date: " + formatted);

Parsing a date string

String dateStr = "25-12-2025";
LocalDate parsedDate = LocalDate.parse(dateStr, formatter);

System.out.println("Parsed Date: " + parsedDate);

4. Adding and Subtracting Dates

The date-time classes include methods like plusDays(), minusMonths(), etc.

LocalDate today = LocalDate.now();
LocalDate nextWeek = today.plusWeeks(1);
LocalDate lastMonth = today.minusMonths(1);

System.out.println("Next Week: " + nextWeek);
System.out.println("Last Month: " + lastMonth);

5. Comparing Dates

You can compare dates using methods like isBefore(), isAfter(), and isEqual().

LocalDate d1 = LocalDate.of(2025, 5, 1);
LocalDate d2 = LocalDate.of(2025, 6, 1);

System.out.println(d1.isBefore(d2)); // true
System.out.println(d1.isAfter(d2));  // false

6. Calculating Differences Between Dates

Use Period for dates and Duration for times.

Difference in days, months, years

LocalDate start = LocalDate.of(2023, 1, 1);
LocalDate end = LocalDate.of(2025, 1, 1);

Period period = Period.between(start, end);
System.out.println(period.getYears() + " years, " +
                   period.getMonths() + " months, " +
                   period.getDays() + " days");

Difference in hours, minutes, seconds

LocalTime t1 = LocalTime.of(10, 0);
LocalTime t2 = LocalTime.of(15, 30);

Duration duration = Duration.between(t1, t2);
System.out.println("Hours: " + duration.toHours());
System.out.println("Minutes: " + duration.toMinutes());

7. Converting Between Old and New Date APIs

If you are integrating with older codebases, you may need conversions.

From Date to Instant

Date oldDate = new Date();
Instant instant = oldDate.toInstant();

From Instant to LocalDateTime

LocalDateTime dt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

From LocalDateTime to Date

Date backToDate = Date.from(dt.atZone(ZoneId.systemDefault()).toInstant());

8. Working With Periods and Durations

Period (Date-based)

Used for years, months, and days.

Period period = Period.of(0, 2, 10); // 2 months and 10 days

Duration (Time-based)

Used for hours, minutes, and seconds.

Duration duration = Duration.ofHours(5);

Conclusion

The Java java.time API offers a clean, modern, and powerful way to handle date and time in your applications. Whether you’re formatting dates, calculating time differences, or working with time zones, the API provides tools that are both intuitive and robust.

If you’re still using legacy date classes, now is the perfect time to adopt the newer API for safer, cleaner, and more maintainable code.

fathibensari
fathibensari
Articles: 3

Leave a Reply

Your email address will not be published. Required fields are marked *