๐Ÿ“Š We use cookies & analytics to improve your experience. Learn more
Latest

Java Programming Foundations Module 4 ยท Lesson 12 of 15

0% Exit to course

Module 4 ยท The standard library, in depth Lesson 12 of 15

Dates, times and Optional

Learning objective

Java's old Date class is a trap; java.time.LocalDate and LocalDateTime are the ones to use. Optional is the return type that says 'this might be missing' instead of returning null.

The concept

LocalDate has a date and no time, LocalDateTime adds the time, ZonedDateTime adds the zone - pick the least you need and daylight-saving bugs disappear.

Optional is for return values, not fields or parameters; used in the wrong place it makes code noisier than the null it replaced.

Java
LocalDate today = LocalDate.now();
LocalDate due   = today.plusDays(7);
long days       = ChronoUnit.DAYS.between(today, due);

Optional<Student> s = repo.find(42);
String name = s.map(Student::getName).orElse("unknown");

Worked example

LocalDate.now().plusDays(7) is a week from today; Optional.ofNullable(find(id)).orElseThrow() turns a missing value into a clear failure.

Your practice task

Compute a due date seven days from today, and write a method that returns an Optional instead of null.

Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.

Key takeaway

LocalDate has a date and no time, LocalDateTime adds the time, ZonedDateTime adds the zone - pick the least you need and daylight-saving bugs disappear.

Create free account or sign in

Almost there

15 lessons left of 15

Finish every lesson to unlock the certificate. Each one ends in a practice task โ€” do them and the final project brief writes itself.

Next recommended course Python for Absolute Beginners