Master Java 8 Date & Time API: Practical Examples and Tips
This article introduces Java 8's new date‑time API, explains its advantages over the old java.util.Date and SimpleDateFormat, lists the essential classes such as Instant, LocalDate, LocalTime, ZonedDateTime, and provides step‑by‑step code examples for common operations like getting the current date, manipulating specific dates, handling time zones, and formatting.
Introduction
With the arrival of lambda expressions, streams, and a series of small optimizations, Java 8 introduced a brand‑new date‑time API to address the shortcomings of the old java.util.Date and SimpleDateFormat, which were mutable and not thread‑safe.
The new API clarifies date‑time concepts by providing distinct types for instant, duration, date, time, time‑zone and period, and it inherits the human‑readable and computer‑friendly handling from the Joda library. All classes in java.time are immutable and thread‑safe.
Key Classes
Instant – an instantaneous point on the timeline.
LocalDate – a date without time, e.g., 2014‑01‑14.
LocalTime – a time without date.
LocalDateTime – combines date and time without zone information.
ZonedDateTime – the most complete date‑time, including zone and offset.
Additional useful classes include ZoneOffset, ZoneId, and DateTimeFormatter for parsing and formatting.
Practical Examples
1. Get the current date
public void getCurrentDate() {
LocalDate today = LocalDate.now();
System.out.println("Today's Local date : " + today);
// comparison with old API
Date date = new Date();
System.out.println(date);
}2. Get year, month, day
public void getDetailDate() {
LocalDate today = LocalDate.now();
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();
System.out.printf("Year : %d Month : %d day : %d%n", year, month, day);
}3. Handle a specific date
public void handleSpecilDate() {
LocalDate dateOfBirth = LocalDate.of(2018, 1, 21);
System.out.println("The specil date is : " + dateOfBirth);
}4. Get year, month, day values separately
public void getDetailDate() {
LocalDate today = LocalDate.now();
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();
System.out.printf("Year : %d Month : %d day : %d%n", year, month, day);
}5. Compare two dates for equality
public void compareDate() {
LocalDate today = LocalDate.now();
LocalDate date1 = LocalDate.of(2018, 1, 21);
if (date1.equals(today)) {
System.out.printf("TODAY %s and DATE1 %s are same date %n", today, date1);
}
}6. Check periodic events (birthday) with MonthDay
public void cycleDate() {
LocalDate today = LocalDate.now();
LocalDate dateOfBirth = LocalDate.of(2018, 1, 21);
MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());
MonthDay currentMonthDay = MonthDay.from(today);
if (currentMonthDay.equals(birthday)) {
System.out.println("Many Many happy returns of the day !!");
} else {
System.out.println("Sorry, today is not your birthday");
}
}7. Get current time
public void getCurrentTime() {
LocalTime time = LocalTime.now();
System.out.println("local time now : " + time);
}8. Add hours to a time
public void plusHours() {
LocalTime time = LocalTime.now();
LocalTime newTime = time.plusHours(2); // add two hours
System.out.println("Time after 2 hours : " + newTime);
}9. Calculate date one week later
public void nextWeek() {
LocalDate today = LocalDate.now();
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
System.out.println("Today is : " + today);
System.out.println("Date after 1 week : " + nextWeek);
}10. Calculate date one year before/after
public void minusDate() {
LocalDate today = LocalDate.now();
LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
System.out.println("Date before 1 year : " + previousYear);
LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
System.out.println("Date after 1 year : " + nextYear);
}11. Use Clock for timestamps and zones
public void clock() {
Clock clock = Clock.systemUTC();
System.out.println("Clock : " + clock);
Clock defaultClock = Clock.systemDefaultZone();
System.out.println("Clock : " + defaultClock);
}12. Compare dates (before/after)
public void isBeforeOrIsAfter() {
LocalDate today = LocalDate.now();
LocalDate tomorrow = LocalDate.of(2018, 1, 29);
if (tomorrow.isAfter(today)) {
System.out.println("Tomorrow comes after today");
}
LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);
if (yesterday.isBefore(today)) {
System.out.println("Yesterday is day before today");
}
}13. Work with time zones
public void getZoneTime() {
ZoneId america = ZoneId.of("America/New_York");
LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime dateInNY = ZonedDateTime.of(localDateTime, america);
System.out.println("Current date and time in specific zone : " + dateInNY);
}14. Use YearMonth for fixed dates (e.g., credit‑card expiry)
public void checkCardExpiry() {
YearMonth current = YearMonth.now();
System.out.printf("Days in month year %s: %d%n", current, current.lengthOfMonth());
YearMonth creditCardExpiry = YearMonth.of(2028, Month.FEBRUARY);
System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
}15. Check leap year
public void isLeapYear() {
LocalDate today = LocalDate.now();
if (today.isLeapYear()) {
System.out.println("This year is Leap year");
} else {
System.out.println("2018 is not a Leap year");
}
}16. Calculate days/months between dates
public void calcDateDays() {
LocalDate today = LocalDate.now();
LocalDate java8Release = LocalDate.of(2018, Month.MAY, 14);
Period period = Period.between(today, java8Release);
System.out.println("Months left between today and Java 8 release : " + period.getMonths());
}17. Date‑time with zone offset
public void ZoneOffset() {
LocalDateTime datetime = LocalDateTime.of(2018, Month.FEBRUARY, 14, 19, 30);
ZoneOffset offset = ZoneOffset.of("+05:30");
OffsetDateTime date = OffsetDateTime.of(datetime, offset);
System.out.println("Date and Time with timezone offset in Java : " + date);
}18. Get current timestamp with Instant
public void getTimestamp() {
Instant timestamp = Instant.now();
System.out.println("What is value of this instant " + timestamp);
}19. Parse and format dates with predefined formatters
public void formateDate() {
String day = "20180210";
LocalDate formatted = LocalDate.parse(day, DateTimeFormatter.BASIC_ISO_DATE);
System.out.printf("Date generated from String %s is %s %n", day, formatted);
}Summary
The Java 8 date‑time API provides immutable, thread‑safe classes such as Instant, LocalDate, LocalTime, LocalDateTime, ZonedDateTime, and utilities like ZoneId and DateTimeFormatter. It replaces the mutable java.util.Date and non‑thread‑safe SimpleDateFormat, offering a clear separation of date, time, and time‑zone concepts.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
