Date & Time
DateTime Calculations
When calculating ages, finding days until deadlines, or scheduling future events, you need date arithmetic. Java provides Period for date-based amounts and Duration for time-based amounts, making these calculations precise and readable.
DateTime calculations perform arithmetic with dates and times. Java uses Period for date-based amounts and Duration for time-based amounts.
Date Arithmetic
Arithmetic.java
// Add and subtract dates
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class Arithmetic {
public static void main(String[] args) {
LocalDate today = ;
System.out.println("Today: " + today);
System.out.println();
// Add days
System.out.println("Add days:");
System.out.println("Tomorrow: " + today.plusDays(1));
System.out.println("+7 days: " + today.plusDays(7));
System.out.println("+30 days: " + today.plusDays(30));
// Add weeks
System.out.println("\nAdd weeks:");
System.out.println("+1 week: " + today.plusWeeks(1));
System.out.println("+4 weeks: " + today.plusWeeks(4));
// Add months
System.out.println("\nAdd months:");
System.out.println("+1 month: " + today.plusMonths(1));
System.out.println("+3 months: " + today.plusMonths(3));
System.out.println("+12 months: " + today.plusMonths(12));
// Add years
System.out.println("\nAdd years:");
System.out.println("+1 year: " + today.plusYears(1));
System.out.println("+5 years: " + today.plusYears(5));
// Subtract
System.out.println("\nSubtract:");
System.out.println("Yesterday: " + today.minusDays(1));
System.out.println("-1 week: " + today.minusWeeks(1));
System.out.println("-1 month: " + today.minusMonths(1));
System.out.println("-1 year: " + today.minusYears(1));
// Chaining
System.out.println("\nChaining:");
LocalDate future = today.plusMonths(3).plusDays(15);
System.out.println("+3 months +15 days: " + future);
// Period
System.out.println("\nUsing Period:");
Period p1 = Period.ofDays(7);
System.out.println("Period of 7 days: " + today.plus(p1));
Period p2 = Period.ofMonths(2);
System.out.println("Period of 2 months: " + today.plus(p2));
Period p3 = Period.of(1, 3, 15); // 1 year, 3 months, 15 days
System.out.println("Period 1y 3m 15d: " + today.plus(p3));
// DateTime arithmetic
System.out.println("\nDateTime arithmetic:");
LocalDateTime now = LocalDateTime.of(2025, 1, 29, 14, 30, 0);
System.out.println("Now: " + now);
System.out.println("+2 hours: " + now.plusHours(2));
System.out.println("+30 minutes: " + now.plusMinutes(30));
System.out.println("+1 day 2 hours: " + now.plusDays(1).plusHours(2));
// End of periods
System.out.println("\nEnd of periods:");
System.out.println("End of week: " + today.plusWeeks(1));
System.out.println("End of month: " + today.plusMonths(1));
System.out.println("End of quarter: " + today.plusMonths(3));
System.out.println("End of year: " + today.plusYears(1));
// Practical examples
System.out.println("\nPractical examples:");
System.out.println("30-day trial ends: " + today.plusDays(30));
System.out.println("Quarterly review: " + today.plusMonths(3));
System.out.println("Annual renewal: " + today.plusYears(1));
System.out.println("Two weeks notice: " + today.plusWeeks(2));
}
}
// Add and subtract dates
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class Arithmetic {
public static void main(String[] args) {
LocalDate today = ;
System.out.println("Today: " + today);
System.out.println();
// Add days
System.out.println("Add days:");
System.out.println("Tomorrow: " + today.plusDays(1));
System.out.println("+7 days: " + today.plusDays(7));
System.out.println("+30 days: " + today.plusDays(30));
// Add weeks
System.out.println("\nAdd weeks:");
System.out.println("+1 week: " + today.plusWeeks(1));
System.out.println("+4 weeks: " + today.plusWeeks(4));
// Add months
System.out.println("\nAdd months:");
System.out.println("+1 month: " + today.plusMonths(1));
System.out.println("+3 months: " + today.plusMonths(3));
System.out.println("+12 months: " + today.plusMonths(12));
// Add years
System.out.println("\nAdd years:");
System.out.println("+1 year: " + today.plusYears(1));
System.out.println("+5 years: " + today.plusYears(5));
// Subtract
System.out.println("\nSubtract:");
System.out.println("Yesterday: " + today.minusDays(1));
System.out.println("-1 week: " + today.minusWeeks(1));
System.out.println("-1 month: " + today.minusMonths(1));
System.out.println("-1 year: " + today.minusYears(1));
// Chaining
System.out.println("\nChaining:");
LocalDate future = today.plusMonths(3).plusDays(15);
System.out.println("+3 months +15 days: " + future);
// Period
System.out.println("\nUsing Period:");
Period p1 = Period.ofDays(7);
System.out.println("Period of 7 days: " + today.plus(p1));
Period p2 = Period.ofMonths(2);
System.out.println("Period of 2 months: " + today.plus(p2));
Period p3 = Period.of(1, 3, 15); // 1 year, 3 months, 15 days
System.out.println("Period 1y 3m 15d: " + today.plus(p3));
// DateTime arithmetic
System.out.println("\nDateTime arithmetic:");
LocalDateTime now = LocalDateTime.of(2025, 1, 29, 14, 30, 0);
System.out.println("Now: " + now);
System.out.println("+2 hours: " + now.plusHours(2));
System.out.println("+30 minutes: " + now.plusMinutes(30));
System.out.println("+1 day 2 hours: " + now.plusDays(1).plusHours(2));
// End of periods
System.out.println("\nEnd of periods:");
System.out.println("End of week: " + today.plusWeeks(1));
System.out.println("End of month: " + today.plusMonths(1));
System.out.println("End of quarter: " + today.plusMonths(3));
System.out.println("End of year: " + today.plusYears(1));
// Practical examples
System.out.println("\nPractical examples:");
System.out.println("30-day trial ends: " + today.plusDays(30));
System.out.println("Quarterly review: " + today.plusMonths(3));
System.out.println("Annual renewal: " + today.plusYears(1));
System.out.println("Two weeks notice: " + today.plusWeeks(2));
}
}
Period
Represents a date-based amount of time in years, months, and days. Used for calendar calculations.
Calculating Differences
Difference.java
// Calculate differences
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
public class Difference {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2025, 1, 1);
LocalDate end = ;
System.out.println("Start: " + start);
System.out.println("End: " + end);
System.out.println();
// Period between
Period period = Period.between(start, end);
System.out.println("Period between:");
System.out.println("Years: " + period.getYears());
System.out.println("Months: " + period.getMonths());
System.out.println("Days: " + period.getDays());
System.out.println("Full period: " + period);
// Total days
long days = ChronoUnit.DAYS.between(start, end);
System.out.println("\nTotal days: " + days);
// Other units
System.out.println("\nOther units:");
System.out.println("Weeks: " + ChronoUnit.WEEKS.between(start, end));
System.out.println("Months: " + ChronoUnit.MONTHS.between(start, end));
System.out.println("Years: " + ChronoUnit.YEARS.between(start, end));
// Different date pairs
System.out.println("\nDifferent pairs:");
LocalDate d1 = LocalDate.of(2020, 1, 15);
LocalDate d2 = LocalDate.of(2025, 3, 20);
Period p = Period.between(d1, d2);
System.out.println(d1 + " to " + d2);
System.out.println("Period: " + p.getYears() + "y " + p.getMonths() + "m " + p.getDays() + "d");
System.out.println("Total days: " + ChronoUnit.DAYS.between(d1, d2));
// DateTime differences
System.out.println("\nDateTime differences:");
LocalDateTime dt1 = LocalDateTime.of(2025, 1, 29, 10, 0);
LocalDateTime dt2 = LocalDateTime.of(2025, 1, 29, 15, 30);
Duration duration = Duration.between(dt1, dt2);
System.out.println(dt1 + " to " + dt2);
System.out.println("Duration: " + duration);
System.out.println("Hours: " + duration.toHours());
System.out.println("Minutes: " + duration.toMinutes());
System.out.println("Seconds: " + duration.toSeconds());
// Time units
System.out.println("\nTime units between:");
System.out.println("Hours: " + ChronoUnit.HOURS.between(dt1, dt2));
System.out.println("Minutes: " + ChronoUnit.MINUTES.between(dt1, dt2));
System.out.println("Seconds: " + ChronoUnit.SECONDS.between(dt1, dt2));
// Absolute difference
System.out.println("\nAbsolute difference:");
LocalDate past = LocalDate.of(2020, 1, 1);
LocalDate future = LocalDate.of(2030, 1, 1);
System.out.println("Past to future: " + ChronoUnit.DAYS.between(past, future));
System.out.println("Future to past: " + ChronoUnit.DAYS.between(future, past));
System.out.println("Absolute: " + Math.abs(ChronoUnit.DAYS.between(future, past)));
// Practical examples
System.out.println("\nPractical examples:");
LocalDate birthday = LocalDate.of(1990, 3, 15);
LocalDate today = LocalDate.of(2025, 1, 29);
long age = ChronoUnit.YEARS.between(birthday, today);
System.out.println("Age: " + age + " years");
LocalDate projectStart = LocalDate.of(2025, 1, 1);
LocalDate projectEnd = LocalDate.of(2025, 3, 31);
long projectDays = ChronoUnit.DAYS.between(projectStart, projectEnd);
System.out.println("Project duration: " + projectDays + " days");
LocalDate subscriptionStart = LocalDate.of(2024, 1, 1);
LocalDate subscriptionEnd = LocalDate.of(2025, 1, 1);
long subscriptionMonths = ChronoUnit.MONTHS.between(subscriptionStart, subscriptionEnd);
System.out.println("Subscription: " + subscriptionMonths + " months");
}
}
// Calculate differences
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
public class Difference {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2025, 1, 1);
LocalDate end = ;
System.out.println("Start: " + start);
System.out.println("End: " + end);
System.out.println();
// Period between
Period period = Period.between(start, end);
System.out.println("Period between:");
System.out.println("Years: " + period.getYears());
System.out.println("Months: " + period.getMonths());
System.out.println("Days: " + period.getDays());
System.out.println("Full period: " + period);
// Total days
long days = ChronoUnit.DAYS.between(start, end);
System.out.println("\nTotal days: " + days);
// Other units
System.out.println("\nOther units:");
System.out.println("Weeks: " + ChronoUnit.WEEKS.between(start, end));
System.out.println("Months: " + ChronoUnit.MONTHS.between(start, end));
System.out.println("Years: " + ChronoUnit.YEARS.between(start, end));
// Different date pairs
System.out.println("\nDifferent pairs:");
LocalDate d1 = LocalDate.of(2020, 1, 15);
LocalDate d2 = LocalDate.of(2025, 3, 20);
Period p = Period.between(d1, d2);
System.out.println(d1 + " to " + d2);
System.out.println("Period: " + p.getYears() + "y " + p.getMonths() + "m " + p.getDays() + "d");
System.out.println("Total days: " + ChronoUnit.DAYS.between(d1, d2));
// DateTime differences
System.out.println("\nDateTime differences:");
LocalDateTime dt1 = LocalDateTime.of(2025, 1, 29, 10, 0);
LocalDateTime dt2 = LocalDateTime.of(2025, 1, 29, 15, 30);
Duration duration = Duration.between(dt1, dt2);
System.out.println(dt1 + " to " + dt2);
System.out.println("Duration: " + duration);
System.out.println("Hours: " + duration.toHours());
System.out.println("Minutes: " + duration.toMinutes());
System.out.println("Seconds: " + duration.toSeconds());
// Time units
System.out.println("\nTime units between:");
System.out.println("Hours: " + ChronoUnit.HOURS.between(dt1, dt2));
System.out.println("Minutes: " + ChronoUnit.MINUTES.between(dt1, dt2));
System.out.println("Seconds: " + ChronoUnit.SECONDS.between(dt1, dt2));
// Absolute difference
System.out.println("\nAbsolute difference:");
LocalDate past = LocalDate.of(2020, 1, 1);
LocalDate future = LocalDate.of(2030, 1, 1);
System.out.println("Past to future: " + ChronoUnit.DAYS.between(past, future));
System.out.println("Future to past: " + ChronoUnit.DAYS.between(future, past));
System.out.println("Absolute: " + Math.abs(ChronoUnit.DAYS.between(future, past)));
// Practical examples
System.out.println("\nPractical examples:");
LocalDate birthday = LocalDate.of(1990, 3, 15);
LocalDate today = LocalDate.of(2025, 1, 29);
long age = ChronoUnit.YEARS.between(birthday, today);
System.out.println("Age: " + age + " years");
LocalDate projectStart = LocalDate.of(2025, 1, 1);
LocalDate projectEnd = LocalDate.of(2025, 3, 31);
long projectDays = ChronoUnit.DAYS.between(projectStart, projectEnd);
System.out.println("Project duration: " + projectDays + " days");
LocalDate subscriptionStart = LocalDate.of(2024, 1, 1);
LocalDate subscriptionEnd = LocalDate.of(2025, 1, 1);
long subscriptionMonths = ChronoUnit.MONTHS.between(subscriptionStart, subscriptionEnd);
System.out.println("Subscription: " + subscriptionMonths + " months");
}
}
Duration
Represents a time-based amount in seconds and nanoseconds. Used for precise time measurements.
Age Calculation
Age.java
// Age calculation
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class Age {
public static void main(String[] args) {
LocalDate birthdate = ;
LocalDate today = LocalDate.of(2025, 1, 29);
System.out.println("Birthdate: " + birthdate);
System.out.println("Today: " + today);
System.out.println();
// Age in years
long ageYears = ChronoUnit.YEARS.between(birthdate, today);
System.out.println("Age (years): " + ageYears);
// Age as period
Period age = Period.between(birthdate, today);
System.out.println("Age (period): " + age.getYears() + " years, " +
age.getMonths() + " months, " + age.getDays() + " days");
// Age in different units
System.out.println("\nAge in different units:");
System.out.println("Years: " + ChronoUnit.YEARS.between(birthdate, today));
System.out.println("Months: " + ChronoUnit.MONTHS.between(birthdate, today));
System.out.println("Days: " + ChronoUnit.DAYS.between(birthdate, today));
// Next birthday
LocalDate nextBirthday = birthdate.withYear(today.getYear());
if (nextBirthday.isBefore(today) || nextBirthday.isEqual(today)) {
nextBirthday = nextBirthday.plusYears(1);
}
System.out.println("\nNext birthday: " + nextBirthday);
System.out.println("Days until birthday: " + ChronoUnit.DAYS.between(today, nextBirthday));
// Age at specific date
System.out.println("\nAge at specific dates:");
LocalDate[] checkDates = {
LocalDate.of(2020, 1, 1),
LocalDate.of(2025, 1, 1),
LocalDate.of(2030, 12, 31)
};
for (LocalDate checkDate : checkDates) {
long ageAt = ChronoUnit.YEARS.between(birthdate, checkDate);
System.out.println("Age on " + checkDate + ": " + ageAt);
}
// Multiple people
System.out.println("\nMultiple people:");
LocalDate[][] people = {
{LocalDate.of(1990, 3, 15), today},
{LocalDate.of(1985, 7, 22), today},
{LocalDate.of(2000, 11, 30), today}
};
for (int i = 0; i < people.length; i++) {
LocalDate birth = people[i][0];
LocalDate current = people[i][1];
Period p = Period.between(birth, current);
System.out.println("Person " + (i + 1) + " (born " + birth + "): " +
p.getYears() + "y " + p.getMonths() + "m " + p.getDays() + "d");
}
// Age verification
System.out.println("\nAge verification:");
System.out.println("Is 18 or older? " + isAdult(birthdate, today));
System.out.println("Is 21 or older? " + isMinimumAge(birthdate, today, 21));
System.out.println("Is senior (65+)? " + isMinimumAge(birthdate, today, 65));
// Age groups
System.out.println("\nAge group:");
System.out.println(getAgeGroup(birthdate, today));
// Time until milestone
System.out.println("\nMilestone birthdays:");
int[] milestones = {18, 21, 30, 40, 50};
int currentAge = (int) ChronoUnit.YEARS.between(birthdate, today);
for (int milestone : milestones) {
if (milestone > currentAge) {
LocalDate milestoneDate = birthdate.plusYears(milestone);
long daysUntil = ChronoUnit.DAYS.between(today, milestoneDate);
System.out.println(milestone + " years: " + milestoneDate +
" (in " + daysUntil + " days)");
}
}
// Retirement calculation
System.out.println("\nRetirement:");
int retirementAge = 65;
LocalDate retirementDate = birthdate.plusYears(retirementAge);
long yearsToRetirement = ChronoUnit.YEARS.between(today, retirementDate);
long daysToRetirement = ChronoUnit.DAYS.between(today, retirementDate);
System.out.println("Retirement date: " + retirementDate);
System.out.println("Years to retirement: " + yearsToRetirement);
System.out.println("Days to retirement: " + daysToRetirement);
}
public static boolean isAdult(LocalDate birthdate, LocalDate currentDate) {
return ChronoUnit.YEARS.between(birthdate, currentDate) >= 18;
}
public static boolean isMinimumAge(LocalDate birthdate, LocalDate currentDate, int minAge) {
return ChronoUnit.YEARS.between(birthdate, currentDate) >= minAge;
}
public static String getAgeGroup(LocalDate birthdate, LocalDate currentDate) {
long age = ChronoUnit.YEARS.between(birthdate, currentDate);
if (age < 13) return "Child";
if (age < 18) return "Teenager";
if (age < 65) return "Adult";
return "Senior";
}
}
// Age calculation
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class Age {
public static void main(String[] args) {
LocalDate birthdate = ;
LocalDate today = LocalDate.of(2025, 1, 29);
System.out.println("Birthdate: " + birthdate);
System.out.println("Today: " + today);
System.out.println();
// Age in years
long ageYears = ChronoUnit.YEARS.between(birthdate, today);
System.out.println("Age (years): " + ageYears);
// Age as period
Period age = Period.between(birthdate, today);
System.out.println("Age (period): " + age.getYears() + " years, " +
age.getMonths() + " months, " + age.getDays() + " days");
// Age in different units
System.out.println("\nAge in different units:");
System.out.println("Years: " + ChronoUnit.YEARS.between(birthdate, today));
System.out.println("Months: " + ChronoUnit.MONTHS.between(birthdate, today));
System.out.println("Days: " + ChronoUnit.DAYS.between(birthdate, today));
// Next birthday
LocalDate nextBirthday = birthdate.withYear(today.getYear());
if (nextBirthday.isBefore(today) || nextBirthday.isEqual(today)) {
nextBirthday = nextBirthday.plusYears(1);
}
System.out.println("\nNext birthday: " + nextBirthday);
System.out.println("Days until birthday: " + ChronoUnit.DAYS.between(today, nextBirthday));
// Age at specific date
System.out.println("\nAge at specific dates:");
LocalDate[] checkDates = {
LocalDate.of(2020, 1, 1),
LocalDate.of(2025, 1, 1),
LocalDate.of(2030, 12, 31)
};
for (LocalDate checkDate : checkDates) {
long ageAt = ChronoUnit.YEARS.between(birthdate, checkDate);
System.out.println("Age on " + checkDate + ": " + ageAt);
}
// Multiple people
System.out.println("\nMultiple people:");
LocalDate[][] people = {
{LocalDate.of(1990, 3, 15), today},
{LocalDate.of(1985, 7, 22), today},
{LocalDate.of(2000, 11, 30), today}
};
for (int i = 0; i < people.length; i++) {
LocalDate birth = people[i][0];
LocalDate current = people[i][1];
Period p = Period.between(birth, current);
System.out.println("Person " + (i + 1) + " (born " + birth + "): " +
p.getYears() + "y " + p.getMonths() + "m " + p.getDays() + "d");
}
// Age verification
System.out.println("\nAge verification:");
System.out.println("Is 18 or older? " + isAdult(birthdate, today));
System.out.println("Is 21 or older? " + isMinimumAge(birthdate, today, 21));
System.out.println("Is senior (65+)? " + isMinimumAge(birthdate, today, 65));
// Age groups
System.out.println("\nAge group:");
System.out.println(getAgeGroup(birthdate, today));
// Time until milestone
System.out.println("\nMilestone birthdays:");
int[] milestones = {18, 21, 30, 40, 50};
int currentAge = (int) ChronoUnit.YEARS.between(birthdate, today);
for (int milestone : milestones) {
if (milestone > currentAge) {
LocalDate milestoneDate = birthdate.plusYears(milestone);
long daysUntil = ChronoUnit.DAYS.between(today, milestoneDate);
System.out.println(milestone + " years: " + milestoneDate +
" (in " + daysUntil + " days)");
}
}
// Retirement calculation
System.out.println("\nRetirement:");
int retirementAge = 65;
LocalDate retirementDate = birthdate.plusYears(retirementAge);
long yearsToRetirement = ChronoUnit.YEARS.between(today, retirementDate);
long daysToRetirement = ChronoUnit.DAYS.between(today, retirementDate);
System.out.println("Retirement date: " + retirementDate);
System.out.println("Years to retirement: " + yearsToRetirement);
System.out.println("Days to retirement: " + daysToRetirement);
}
public static boolean isAdult(LocalDate birthdate, LocalDate currentDate) {
return ChronoUnit.YEARS.between(birthdate, currentDate) >= 18;
}
public static boolean isMinimumAge(LocalDate birthdate, LocalDate currentDate, int minAge) {
return ChronoUnit.YEARS.between(birthdate, currentDate) >= minAge;
}
public static String getAgeGroup(LocalDate birthdate, LocalDate currentDate) {
long age = ChronoUnit.YEARS.between(birthdate, currentDate);
if (age < 13) return "Child";
if (age < 18) return "Teenager";
if (age < 65) return "Adult";
return "Senior";
}
}
Day of Week
Dayofweek.java
// Day of week operations
import java.time.LocalDate;
import java.time.DayOfWeek;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.ChronoUnit;
public class Dayofweek {
public static void main(String[] args) {
LocalDate date = ;
System.out.println("Date: " + date);
System.out.println();
// Get day of week
DayOfWeek dow = date.getDayOfWeek();
System.out.println("Day of week: " + dow);
System.out.println("Day value (1=Mon, 7=Sun): " + dow.getValue());
// Check specific days
System.out.println("\nCheck specific days:");
System.out.println("Is Monday? " + (dow == DayOfWeek.MONDAY));
System.out.println("Is weekend? " + (dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY));
// Next/previous specific day
System.out.println("\nNext/previous specific day:");
LocalDate nextMonday = date.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
System.out.println("Next Monday: " + nextMonday);
LocalDate prevFriday = date.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));
System.out.println("Previous Friday: " + prevFriday);
// Next or same
LocalDate nextOrSameMon = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));
System.out.println("Next or same Monday: " + nextOrSameMon);
// Days in week
System.out.println("\nAll days of week:");
for (DayOfWeek day : DayOfWeek.values()) {
System.out.println(day.getValue() + ": " + day);
}
// Week navigation
System.out.println("\nWeek navigation:");
LocalDate monday = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
System.out.println("This week:");
for (int i = 0; i < 7; i++) {
LocalDate d = monday.plusDays(i);
System.out.println(d.getDayOfWeek() + ": " + d);
}
// Business days
System.out.println("\nBusiness days:");
System.out.println("Next business day: " + nextBusinessDay(date));
System.out.println("Previous business day: " + previousBusinessDay(date));
// Count business days
LocalDate start = LocalDate.of(2025, 1, 27); // Monday
LocalDate end = LocalDate.of(2025, 2, 7); // Friday
System.out.println("\nBusiness days from " + start + " to " + end + ": " +
countBusinessDays(start, end));
// Weekend check
System.out.println("\nWeekend check:");
LocalDate[] testDates = {
LocalDate.of(2025, 1, 27), // Monday
LocalDate.of(2025, 2, 1), // Saturday
LocalDate.of(2025, 2, 2) // Sunday
};
for (LocalDate d : testDates) {
System.out.println(d + " (" + d.getDayOfWeek() + "): " +
(isWeekend(d) ? "Weekend" : "Weekday"));
}
// Add business days
System.out.println("\nAdd business days:");
LocalDate today = LocalDate.of(2025, 1, 29); // Wednesday
int businessDaysToAdd = ;
System.out.println("Today: " + today + " (" + today.getDayOfWeek() + ")");
System.out.println("+" + businessDaysToAdd + " business days: " + addBusinessDays(today, businessDaysToAdd));
}
public static LocalDate nextBusinessDay(LocalDate date) {
LocalDate next = date.plusDays(1);
while (isWeekend(next)) {
next = next.plusDays(1);
}
return next;
}
public static LocalDate previousBusinessDay(LocalDate date) {
LocalDate prev = date.minusDays(1);
while (isWeekend(prev)) {
prev = prev.minusDays(1);
}
return prev;
}
public static boolean isWeekend(LocalDate date) {
DayOfWeek dow = date.getDayOfWeek();
return dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY;
}
public static long countBusinessDays(LocalDate start, LocalDate end) {
long count = 0;
LocalDate current = start;
while (!current.isAfter(end)) {
if (!isWeekend(current)) {
count++;
}
current = current.plusDays(1);
}
return count;
}
public static LocalDate addBusinessDays(LocalDate date, int days) {
LocalDate result = date;
int added = 0;
while (added < days) {
result = result.plusDays(1);
if (!isWeekend(result)) {
added++;
}
}
return result;
}
}
// Day of week operations
import java.time.LocalDate;
import java.time.DayOfWeek;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.ChronoUnit;
public class Dayofweek {
public static void main(String[] args) {
LocalDate date = ;
System.out.println("Date: " + date);
System.out.println();
// Get day of week
DayOfWeek dow = date.getDayOfWeek();
System.out.println("Day of week: " + dow);
System.out.println("Day value (1=Mon, 7=Sun): " + dow.getValue());
// Check specific days
System.out.println("\nCheck specific days:");
System.out.println("Is Monday? " + (dow == DayOfWeek.MONDAY));
System.out.println("Is weekend? " + (dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY));
// Next/previous specific day
System.out.println("\nNext/previous specific day:");
LocalDate nextMonday = date.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
System.out.println("Next Monday: " + nextMonday);
LocalDate prevFriday = date.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));
System.out.println("Previous Friday: " + prevFriday);
// Next or same
LocalDate nextOrSameMon = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));
System.out.println("Next or same Monday: " + nextOrSameMon);
// Days in week
System.out.println("\nAll days of week:");
for (DayOfWeek day : DayOfWeek.values()) {
System.out.println(day.getValue() + ": " + day);
}
// Week navigation
System.out.println("\nWeek navigation:");
LocalDate monday = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
System.out.println("This week:");
for (int i = 0; i < 7; i++) {
LocalDate d = monday.plusDays(i);
System.out.println(d.getDayOfWeek() + ": " + d);
}
// Business days
System.out.println("\nBusiness days:");
System.out.println("Next business day: " + nextBusinessDay(date));
System.out.println("Previous business day: " + previousBusinessDay(date));
// Count business days
LocalDate start = LocalDate.of(2025, 1, 27); // Monday
LocalDate end = LocalDate.of(2025, 2, 7); // Friday
System.out.println("\nBusiness days from " + start + " to " + end + ": " +
countBusinessDays(start, end));
// Weekend check
System.out.println("\nWeekend check:");
LocalDate[] testDates = {
LocalDate.of(2025, 1, 27), // Monday
LocalDate.of(2025, 2, 1), // Saturday
LocalDate.of(2025, 2, 2) // Sunday
};
for (LocalDate d : testDates) {
System.out.println(d + " (" + d.getDayOfWeek() + "): " +
(isWeekend(d) ? "Weekend" : "Weekday"));
}
// Add business days
System.out.println("\nAdd business days:");
LocalDate today = LocalDate.of(2025, 1, 29); // Wednesday
int businessDaysToAdd = ;
System.out.println("Today: " + today + " (" + today.getDayOfWeek() + ")");
System.out.println("+" + businessDaysToAdd + " business days: " + addBusinessDays(today, businessDaysToAdd));
}
public static LocalDate nextBusinessDay(LocalDate date) {
LocalDate next = date.plusDays(1);
while (isWeekend(next)) {
next = next.plusDays(1);
}
return next;
}
public static LocalDate previousBusinessDay(LocalDate date) {
LocalDate prev = date.minusDays(1);
while (isWeekend(prev)) {
prev = prev.minusDays(1);
}
return prev;
}
public static boolean isWeekend(LocalDate date) {
DayOfWeek dow = date.getDayOfWeek();
return dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY;
}
public static long countBusinessDays(LocalDate start, LocalDate end) {
long count = 0;
LocalDate current = start;
while (!current.isAfter(end)) {
if (!isWeekend(current)) {
count++;
}
current = current.plusDays(1);
}
return count;
}
public static LocalDate addBusinessDays(LocalDate date, int days) {
LocalDate result = date;
int added = 0;
while (added < days) {
result = result.plusDays(1);
if (!isWeekend(result)) {
added++;
}
}
return result;
}
}
// Day of week operations
import java.time.LocalDate;
import java.time.DayOfWeek;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.ChronoUnit;
public class Dayofweek {
public static void main(String[] args) {
LocalDate date = ;
System.out.println("Date: " + date);
System.out.println();
// Get day of week
DayOfWeek dow = date.getDayOfWeek();
System.out.println("Day of week: " + dow);
System.out.println("Day value (1=Mon, 7=Sun): " + dow.getValue());
// Check specific days
System.out.println("\nCheck specific days:");
System.out.println("Is Monday? " + (dow == DayOfWeek.MONDAY));
System.out.println("Is weekend? " + (dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY));
// Next/previous specific day
System.out.println("\nNext/previous specific day:");
LocalDate nextMonday = date.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
System.out.println("Next Monday: " + nextMonday);
LocalDate prevFriday = date.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));
System.out.println("Previous Friday: " + prevFriday);
// Next or same
LocalDate nextOrSameMon = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));
System.out.println("Next or same Monday: " + nextOrSameMon);
// Days in week
System.out.println("\nAll days of week:");
for (DayOfWeek day : DayOfWeek.values()) {
System.out.println(day.getValue() + ": " + day);
}
// Week navigation
System.out.println("\nWeek navigation:");
LocalDate monday = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
System.out.println("This week:");
for (int i = 0; i < 7; i++) {
LocalDate d = monday.plusDays(i);
System.out.println(d.getDayOfWeek() + ": " + d);
}
// Business days
System.out.println("\nBusiness days:");
System.out.println("Next business day: " + nextBusinessDay(date));
System.out.println("Previous business day: " + previousBusinessDay(date));
// Count business days
LocalDate start = LocalDate.of(2025, 1, 27); // Monday
LocalDate end = LocalDate.of(2025, 2, 7); // Friday
System.out.println("\nBusiness days from " + start + " to " + end + ": " +
countBusinessDays(start, end));
// Weekend check
System.out.println("\nWeekend check:");
LocalDate[] testDates = {
LocalDate.of(2025, 1, 27), // Monday
LocalDate.of(2025, 2, 1), // Saturday
LocalDate.of(2025, 2, 2) // Sunday
};
for (LocalDate d : testDates) {
System.out.println(d + " (" + d.getDayOfWeek() + "): " +
(isWeekend(d) ? "Weekend" : "Weekday"));
}
// Add business days
System.out.println("\nAdd business days:");
LocalDate today = LocalDate.of(2025, 1, 29); // Wednesday
int businessDaysToAdd = ;
System.out.println("Today: " + today + " (" + today.getDayOfWeek() + ")");
System.out.println("+" + businessDaysToAdd + " business days: " + addBusinessDays(today, businessDaysToAdd));
}
public static LocalDate nextBusinessDay(LocalDate date) {
LocalDate next = date.plusDays(1);
while (isWeekend(next)) {
next = next.plusDays(1);
}
return next;
}
public static LocalDate previousBusinessDay(LocalDate date) {
LocalDate prev = date.minusDays(1);
while (isWeekend(prev)) {
prev = prev.minusDays(1);
}
return prev;
}
public static boolean isWeekend(LocalDate date) {
DayOfWeek dow = date.getDayOfWeek();
return dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY;
}
public static long countBusinessDays(LocalDate start, LocalDate end) {
long count = 0;
LocalDate current = start;
while (!current.isAfter(end)) {
if (!isWeekend(current)) {
count++;
}
current = current.plusDays(1);
}
return count;
}
public static LocalDate addBusinessDays(LocalDate date, int days) {
LocalDate result = date;
int added = 0;
while (added < days) {
result = result.plusDays(1);
if (!isWeekend(result)) {
added++;
}
}
return result;
}
}
// Day of week operations
import java.time.LocalDate;
import java.time.DayOfWeek;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.ChronoUnit;
public class Dayofweek {
public static void main(String[] args) {
LocalDate date = ;
System.out.println("Date: " + date);
System.out.println();
// Get day of week
DayOfWeek dow = date.getDayOfWeek();
System.out.println("Day of week: " + dow);
System.out.println("Day value (1=Mon, 7=Sun): " + dow.getValue());
// Check specific days
System.out.println("\nCheck specific days:");
System.out.println("Is Monday? " + (dow == DayOfWeek.MONDAY));
System.out.println("Is weekend? " + (dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY));
// Next/previous specific day
System.out.println("\nNext/previous specific day:");
LocalDate nextMonday = date.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
System.out.println("Next Monday: " + nextMonday);
LocalDate prevFriday = date.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));
System.out.println("Previous Friday: " + prevFriday);
// Next or same
LocalDate nextOrSameMon = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));
System.out.println("Next or same Monday: " + nextOrSameMon);
// Days in week
System.out.println("\nAll days of week:");
for (DayOfWeek day : DayOfWeek.values()) {
System.out.println(day.getValue() + ": " + day);
}
// Week navigation
System.out.println("\nWeek navigation:");
LocalDate monday = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
System.out.println("This week:");
for (int i = 0; i < 7; i++) {
LocalDate d = monday.plusDays(i);
System.out.println(d.getDayOfWeek() + ": " + d);
}
// Business days
System.out.println("\nBusiness days:");
System.out.println("Next business day: " + nextBusinessDay(date));
System.out.println("Previous business day: " + previousBusinessDay(date));
// Count business days
LocalDate start = LocalDate.of(2025, 1, 27); // Monday
LocalDate end = LocalDate.of(2025, 2, 7); // Friday
System.out.println("\nBusiness days from " + start + " to " + end + ": " +
countBusinessDays(start, end));
// Weekend check
System.out.println("\nWeekend check:");
LocalDate[] testDates = {
LocalDate.of(2025, 1, 27), // Monday
LocalDate.of(2025, 2, 1), // Saturday
LocalDate.of(2025, 2, 2) // Sunday
};
for (LocalDate d : testDates) {
System.out.println(d + " (" + d.getDayOfWeek() + "): " +
(isWeekend(d) ? "Weekend" : "Weekday"));
}
// Add business days
System.out.println("\nAdd business days:");
LocalDate today = LocalDate.of(2025, 1, 29); // Wednesday
int businessDaysToAdd = ;
System.out.println("Today: " + today + " (" + today.getDayOfWeek() + ")");
System.out.println("+" + businessDaysToAdd + " business days: " + addBusinessDays(today, businessDaysToAdd));
}
public static LocalDate nextBusinessDay(LocalDate date) {
LocalDate next = date.plusDays(1);
while (isWeekend(next)) {
next = next.plusDays(1);
}
return next;
}
public static LocalDate previousBusinessDay(LocalDate date) {
LocalDate prev = date.minusDays(1);
while (isWeekend(prev)) {
prev = prev.minusDays(1);
}
return prev;
}
public static boolean isWeekend(LocalDate date) {
DayOfWeek dow = date.getDayOfWeek();
return dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY;
}
public static long countBusinessDays(LocalDate start, LocalDate end) {
long count = 0;
LocalDate current = start;
while (!current.isAfter(end)) {
if (!isWeekend(current)) {
count++;
}
current = current.plusDays(1);
}
return count;
}
public static LocalDate addBusinessDays(LocalDate date, int days) {
LocalDate result = date;
int added = 0;
while (added < days) {
result = result.plusDays(1);
if (!isWeekend(result)) {
added++;
}
}
return result;
}
}
Month Operations
MonthCalc.java
// Month operations
import java.time.LocalDate;
import java.time.Month;
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;
public class MonthCalc {
public static void main(String[] args) {
LocalDate date = ;
System.out.println("Date: " + date);
System.out.println();
// Get month
Month month = date.getMonth();
System.out.println("Month: " + month);
System.out.println("Month value: " + month.getValue());
System.out.println("Month length: " + month.length(date.isLeapYear()));
// Month navigation
System.out.println("\nMonth navigation:");
System.out.println("Next month: " + month.plus(1));
System.out.println("Previous month: " + month.minus(1));
// All months
System.out.println("\nAll months:");
for (Month m : Month.values()) {
System.out.println(m.getValue() + ": " + m);
}
// First/last day of month
System.out.println("\nFirst/last day of month:");
LocalDate firstDay = date.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastDay = date.with(TemporalAdjusters.lastDayOfMonth());
System.out.println("First day: " + firstDay);
System.out.println("Last day: " + lastDay);
// YearMonth
System.out.println("\nYearMonth:");
YearMonth ym = YearMonth.of(2025, 1);
System.out.println("YearMonth: " + ym);
System.out.println("Length: " + ym.lengthOfMonth() + " days");
System.out.println("Is leap year: " + ym.isLeapYear());
System.out.println("First day: " + ym.atDay(1));
System.out.println("Last day: " + ym.atEndOfMonth());
// Month lengths
System.out.println("\nMonth lengths (2025):");
for (Month m : Month.values()) {
YearMonth yearMonth = YearMonth.of(2025, m);
System.out.println(m + ": " + yearMonth.lengthOfMonth() + " days");
}
// Leap year comparison
System.out.println("\nFebruary length:");
System.out.println("2024 (leap): " + YearMonth.of(2024, 2).lengthOfMonth());
System.out.println("2025 (not): " + YearMonth.of(2025, 2).lengthOfMonth());
// Month range
System.out.println("\nMonth range:");
LocalDate start = LocalDate.of(2025, 1, 15);
LocalDate end = LocalDate.of(2025, 3, 20);
System.out.println("From " + start + " to " + end);
YearMonth current = YearMonth.from(start);
YearMonth last = YearMonth.from(end);
while (!current.isAfter(last)) {
System.out.println(current + " (" + current.lengthOfMonth() + " days)");
current = current.plusMonths(1);
}
// Add months with overflow
System.out.println("\nAdd months (handle overflow):");
LocalDate jan31 = LocalDate.of(2025, 1, 31);
System.out.println("Jan 31: " + jan31);
System.out.println("+1 month: " + jan31.plusMonths(1)); // Feb 28
System.out.println("+2 months: " + jan31.plusMonths(2)); // Mar 31
// Practical examples
System.out.println("\nPractical examples:");
// Quarterly dates
LocalDate q1End = LocalDate.of(2025, 3, 31);
LocalDate q2End = q1End.plusMonths(3);
LocalDate q3End = q2End.plusMonths(3);
LocalDate q4End = q3End.plusMonths(3);
System.out.println("Q1 end: " + q1End);
System.out.println("Q2 end: " + q2End);
System.out.println("Q3 end: " + q3End);
System.out.println("Q4 end: " + q4End);
// Monthly billing dates
System.out.println("\nMonthly billing dates (starting " + date + "):");
for (int i = 0; i < 6; i++) {
LocalDate billing = date.plusMonths(i);
System.out.println("Month " + i + ": " + billing);
}
// End of each month
System.out.println("\nEnd of each month (2025):");
for (int m = 1; m <= 12; m++) {
LocalDate monthEnd = YearMonth.of(2025, m).atEndOfMonth();
System.out.println(monthEnd.getMonth() + ": " + monthEnd);
}
}
}
// Month operations
import java.time.LocalDate;
import java.time.Month;
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;
public class MonthCalc {
public static void main(String[] args) {
LocalDate date = ;
System.out.println("Date: " + date);
System.out.println();
// Get month
Month month = date.getMonth();
System.out.println("Month: " + month);
System.out.println("Month value: " + month.getValue());
System.out.println("Month length: " + month.length(date.isLeapYear()));
// Month navigation
System.out.println("\nMonth navigation:");
System.out.println("Next month: " + month.plus(1));
System.out.println("Previous month: " + month.minus(1));
// All months
System.out.println("\nAll months:");
for (Month m : Month.values()) {
System.out.println(m.getValue() + ": " + m);
}
// First/last day of month
System.out.println("\nFirst/last day of month:");
LocalDate firstDay = date.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastDay = date.with(TemporalAdjusters.lastDayOfMonth());
System.out.println("First day: " + firstDay);
System.out.println("Last day: " + lastDay);
// YearMonth
System.out.println("\nYearMonth:");
YearMonth ym = YearMonth.of(2025, 1);
System.out.println("YearMonth: " + ym);
System.out.println("Length: " + ym.lengthOfMonth() + " days");
System.out.println("Is leap year: " + ym.isLeapYear());
System.out.println("First day: " + ym.atDay(1));
System.out.println("Last day: " + ym.atEndOfMonth());
// Month lengths
System.out.println("\nMonth lengths (2025):");
for (Month m : Month.values()) {
YearMonth yearMonth = YearMonth.of(2025, m);
System.out.println(m + ": " + yearMonth.lengthOfMonth() + " days");
}
// Leap year comparison
System.out.println("\nFebruary length:");
System.out.println("2024 (leap): " + YearMonth.of(2024, 2).lengthOfMonth());
System.out.println("2025 (not): " + YearMonth.of(2025, 2).lengthOfMonth());
// Month range
System.out.println("\nMonth range:");
LocalDate start = LocalDate.of(2025, 1, 15);
LocalDate end = LocalDate.of(2025, 3, 20);
System.out.println("From " + start + " to " + end);
YearMonth current = YearMonth.from(start);
YearMonth last = YearMonth.from(end);
while (!current.isAfter(last)) {
System.out.println(current + " (" + current.lengthOfMonth() + " days)");
current = current.plusMonths(1);
}
// Add months with overflow
System.out.println("\nAdd months (handle overflow):");
LocalDate jan31 = LocalDate.of(2025, 1, 31);
System.out.println("Jan 31: " + jan31);
System.out.println("+1 month: " + jan31.plusMonths(1)); // Feb 28
System.out.println("+2 months: " + jan31.plusMonths(2)); // Mar 31
// Practical examples
System.out.println("\nPractical examples:");
// Quarterly dates
LocalDate q1End = LocalDate.of(2025, 3, 31);
LocalDate q2End = q1End.plusMonths(3);
LocalDate q3End = q2End.plusMonths(3);
LocalDate q4End = q3End.plusMonths(3);
System.out.println("Q1 end: " + q1End);
System.out.println("Q2 end: " + q2End);
System.out.println("Q3 end: " + q3End);
System.out.println("Q4 end: " + q4End);
// Monthly billing dates
System.out.println("\nMonthly billing dates (starting " + date + "):");
for (int i = 0; i < 6; i++) {
LocalDate billing = date.plusMonths(i);
System.out.println("Month " + i + ": " + billing);
}
// End of each month
System.out.println("\nEnd of each month (2025):");
for (int m = 1; m <= 12; m++) {
LocalDate monthEnd = YearMonth.of(2025, m).atEndOfMonth();
System.out.println(monthEnd.getMonth() + ": " + monthEnd);
}
}
}
TemporalAdjuster
A strategy for adjusting dates, like finding the first/last day of month or next specific weekday.
Period vs Duration
Period: Date-based (days, months, years)Duration: Time-based (hours, minutes, seconds)
Common Operations
- Add/subtract days, months, years
- Calculate duration between dates
- Find day of week, month
- First/last day of month
Exercise: Practical.java
Calculate the number of business days (excluding weekends) between two dates