Java program to convert days to years weeks and days

Quick links

Write a Java program to input days from user and find total years, weeks and days. How to convert days to years weeks and days in Java programming.

Following up our previous mathematical conversion programs in Java. In this post, I will explain how to find number of years, weeks and days in given number of days.

Example
Input

Enter days: 1025

Output

1025 days = 2 year/s, 42 week/s and 1 day/s

Required knowledge

Arithmetic operators, Data types, Basic Input/Output

Days conversion formula

Days to years (ignoring leap year) and weeks conversion formula is expressed as:

1 year = 365 days 
1 week = 7 days

Using above formula we can construct our Java expression to convert days to years, weeks and days.

years = days / 365;
weeks = (days - (years * 365)) / 7;
days  = days - ((years * 365) + (weeks * 7));

Logic to convert days to years weeks and days

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

  1. Input number of days from user, store it in some variable say days.
  2. First we will find years in given days. Divide number of days with 365 to get total years i.e. years = days / 365;.
  3. Next, we will find remaining weeks. To find remaining weeks, divide remaining days after calculated years by 7, say weeks = (days - (years * 365)) / 7;. You can also use a simple approach i.e. weeks = (days % 365) / 7;.
  4. Finally, to find remaining days after years and weeks. Apply formula to calculate remaining days i.e. days = days - ((years * 365) + (weeks * 7));. You can also use a simpler approach i.e. days = (days % 365) % 7;.

Program to convert days to years weeks and days

/**
 * Java program to convert days to years weeks and days.
 */

import java.util.Scanner;

public class DaysConverter {

    public static void main(String[] args) {
        
        Scanner in = new Scanner(System.in);
        
        /* Input number of days from user */
        System.out.print("Enter days: ");
        int days = in.nextInt();

        /* Year, weeks and days conversion  */
        int years = (days / 365);
        int weeks = (days % 365) / 7;
            days  = (days % 365) % 7;

        /* Print total years, weeks and remaining days in given days */
        System.out.println("Year/s = " + years);
        System.out.println("Week/s = " + weeks);
        System.out.println("Day/s  = " + days);
    }
}

Output

Enter days: 373
Year/s = 1
Week/s = 1
Day/s  = 1

Happy coding 😉