Learn how to use Java’s LocalDate class and a custom Day class to simulate and manipulate calendar dates in your Java programs. In this example, we create Day objects for February 28th of four consecutive years, including a leap year, and then advance each by one day to observe the behavior. Perfect for understanding date handling, leap year logic, and object-oriented programming in Java.
Using the Day class of Worked Example 2.1, write a program that
generates a Day object representing February 28 of this year, and three
more such objects that represent February 28 of the next three years.
Advance each object by one day, and print each object. Also print the
expected values
Example 2.1:
public class DaysAlivePrinter
{
public static void main(String[] args)
{
Day jamesGoslingBirthday = new Day(1955, 5, 9);
Day today = new Day();
System.out.print("Today:");
System.out.println(today.toString());
int daysAlive = today.daysFrom(jamesGoslingBirthday);
System.out.print("Day alive: ");
System.out.println(daysAlive);
}
}
Answer
public class DaysAlivePrinter
{
public static void main(String[] args)
{
Day obj1 = new Day(2021, 2, 28);
System.out.println("Before advance
by one day : "+obj1.toString());
obj1.Advance(1);
System.out.println("After advance
by one day : "+obj1.toString());
Day obj2 = new Day(2022, 2, 28);
System.out.println("\nBefore
advance by one day : "+obj2.toString());
obj2.Advance(1);
System.out.println("After advance
by one day : "+obj2.toString());
Day obj3 = new Day(2023, 2, 28);
System.out.println("\nBefore
advance by one day : "+obj3.toString());
obj3.Advance(1);
System.out.println("After advance
by one day : "+obj3.toString());
Day obj4 = new Day(2024, 2, 28);
System.out.println("\nBefore
advance by one day : "+obj4.toString());
obj4.Advance(1);
System.out.println("After advance
by one day : "+obj4.toString());
/*
Day today = new Day();
System.out.print("Today:");
System.out.println(today.toString());
int daysAlive =
today.daysFrom(jamesGoslingBirthday);
System.out.print("Day alive:
");
System.out.println(daysAlive);
*/
}
}
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Day {
LocalDate date;
public Day(){
date = LocalDate.now();
}
public Day(int year , int month , int
day ){
date = LocalDate.of(year, month, day);
}
public int daysFrom(Day
jamesGoslingBirthday ){
return
(int)ChronoUnit.DAYS.between(jamesGoslingBirthday.date, this.date);
}
public void Advance (int day){
date
= date.plusDays(day);
}
public String toString(){
return
date+"";
}
}