Java program to convert days to years weeks and days













Basic Java programming exercises

Java Tutorial Java Exercises Data Structures


Write a Java program to input number of days from user and convert it to years, weeks and days. How to convert days to years, weeks in Java programming. Logic to convert days to years, weeks and days in Java program.








Required knowledge

Arithmetic operators, Data types, Basic input/output


Days conversion formula

1 year = 365 days (Ignoring leap year)

1 week = 7 days

Using this we can define our new formula to compute years and weeks.

year = days / 365

week = (days - (year * 365)) / 7

Logic to convert days to years weeks and days

Step by step descriptive logic to convert days to years, weeks and remaining days -

  1. Input days from user. Store it in some variable say days.

  2. Compute total years using the above conversion table. Which is years = days / 365.

  3. Compute total weeks using the above conversion table. Which is weeks = (days - (year * 365)) / 7.

  4. Compute remaining days using days = days - ((years * 365) + (weeks * 7)).

  5. Finally print all resultant values years, weeks and days.

Program to convert days to years, weeks and days
/** * Java program to convert days in to years, weeks and days */ import java.util.Scanner; class Test { public static void main(String args[]) { int days, years, weeks; Scanner op=new Scanner(System.in); /* Input total number of days from user */ System.out.print("Enter days: "); days=op.nextInt(); /* Conversion */ years = (days / 365); // Ignoring leap year weeks = (days % 365) / 7; days = days - ((years * 365) + (weeks * 7)); /* Print all resultant values */ System.out.println("YEARS: "+years); System.out.println("WEEKS: "+weeks); System.out.println("DAYS: "+days); } }



Output:

Enter days: 831 YEARS: 2 WEEKS: 14 DAYS: 3