Careeroza
Real World Example
EMI Schedule and Delivery Estimate
Banking apps generate EMI due dates (same day every month, adjusted for short months), and e-commerce apps estimate delivery dates that skip Sundays. Both are simple with java.time.
Example
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Main {
static final DateTimeFormatter F = DateTimeFormatter.ofPattern("EEE dd MMM yyyy");
static LocalDate deliveryDate(LocalDate orderDate, int workingDays) {
LocalDate d = orderDate;
int added = 0;
while (added < workingDays) {
d = d.plusDays(1);
if (d.getDayOfWeek() != DayOfWeek.SUNDAY) added++;
}
return d;
}
public static void main(String[] args) {
LocalDate loanStart = LocalDate.of(2024, 1, 31);
System.out.println("EMI schedule (due on the 31st or last day of month):");
for (int i = 1; i <= 4; i++) {
LocalDate due = loanStart.plusMonths(i); // Feb 29, Mar 31, Apr 30...
System.out.println(" EMI " + i + ": " + due.format(F));
}
LocalDate today = LocalDate.of(2024, 3, 25);
LocalDate dueDate = LocalDate.of(2024, 3, 10);
long overdue = ChronoUnit.DAYS.between(dueDate, today);
System.out.println("Overdue by " + overdue + " days, late fee Rs " + overdue * 25);
LocalDate ordered = LocalDate.of(2024, 3, 29); // a Friday
System.out.println("Ordered " + ordered.format(F) + ", arrives by " + deliveryDate(ordered, 3).format(F));
}
}Output
EMI schedule (due on the 31st or last day of month): EMI 1: Thu 29 Feb 2024 EMI 2: Sun 31 Mar 2024 EMI 3: Tue 30 Apr 2024 EMI 4: Fri 31 May 2024 Overdue by 15 days, late fee Rs 375 Ordered Fri 29 Mar 2024, arrives by Tue 02 Apr 2024
Practice
Exercise: Write boolean isEligibleToVote(LocalDate dob, LocalDate onDate) that returns true when the person is at least 18 years old on that date.
Show answer
static boolean isEligibleToVote(LocalDate dob, LocalDate onDate) {
return Period.between(dob, onDate).getYears() >= 18;
// or: !dob.plusYears(18).isAfter(onDate)
}