Module 4 ยท The standard library, in depth Lesson 12 of 15
Dates, times and Optional
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.
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.
Keep your place in this course
A free account saves which lessons you have finished and unlocks the certificate. The lesson itself stays free to read.
Create free account or sign inCourse complete
You finished every lesson.
Your certificate is ready, and the projects you built are the proof to attach to an application.
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.