Java ProgramsBasics & I/OConvert Days to Years, Months and Days

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. 1totalDays holds 1000. 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. 2totalDays / 365 gives 2 whole years, and totalDays % 365 gives 270 leftover days.
  3. 3270 / 30 gives 9 whole months from those leftover days, and 270 % 30 gives 0 days still left over.
  4. 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

Related Programs