Convert Days to Years, Months and Days in Java
intermediate· Basics & I/O · Conversions
Problem
Repeatedly dividing and taking the remainder peels off one unit at a time from a total count — the same technique used to break seconds down into hours, minutes, and seconds.
Given a total number of days, express it as a number of years, months, and remaining days.
Input
totalDays = 1000
Output
2 years, 9 months, 0 days
Java Program
Java
public class ConvertDaysToYearsMonthsAndDays {
public static void main(String[] args) {
int totalDays = 1000;
int years = totalDays / 365; // simplified: treats every year as exactly 365 days, ignoring leap years
int remainingAfterYears = totalDays % 365;
int months = remainingAfterYears / 30; // simplified: treats every month as exactly 30 days
int days = remainingAfterYears % 30;
System.out.println(years + " years, " + months + " months, " + days + " days");
}
}Output
2 years, 9 months, 0 days
Core Logic
Dividing by 365 peels off whole years, then dividing what's left by 30 peels off whole months, leaving only days behind.
How It Works
- 1
totalDaysholds1000. This uses a simplified calendar — 365 days per year and 30 days per month — rather than accounting for leap years or varying month lengths. - 2
totalDays / 365gives2whole years, andtotalDays % 365gives270leftover days. - 3
270 / 30gives9whole months from those leftover days, and270 % 30gives0days still left over. - 4The three results are printed together as
years, months, days.
For
totalDays = 1000: 1000 / 365 = 2 years with 270 days left, then 270 / 30 = 9 months with 0 days left.💡
Key Point: The remainder from the years step (%) becomes the input to the months step — each division-and-remainder pair peels off exactly one unit before handing the rest down to the next, smaller unit.
Key Concepts
intinteger divisionmodulo