In this Java program, we are going to see how we can calculate Year, Week and Days from given total days. We all know that 1 year = 365 (ignoring leap year) and 1 week = 7 days on this basis we can determine the year, week and days from given total no of days.
Logic
If we divide the total number of days by 365 it will return a Year. But to calculate week and days logic is a little different. First, we need the remainder value of (Total days % 365) from this value we can determine total no of weeks and days. To calculate total no of weeks simply divide the remainder value by 7 and to calculate total no of days mode (%) it by 7.
Program
import java.util.Scanner; public class GetYears { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter total number of days : "); int days = scanner.nextInt(); int year = days / 365; int temp = days % 365; int week = temp / 7; days = temp % 7; System.out.printf("Years : %d\nWeeks : %d\nDays : %d", year, week, days); } }
Output
Enter total number of days : 1212
Years : 3
Weeks : 16
Days : 5
Explanation
Calculating year – Divide the total no. of given days with 365.
year = days / 365
Calculating week – Mod the total given days with 365 and divide it with 7 (no of weeks).
temp = days % 365 week = temp / 7
Calculating days – Mod the total given days with 365 and again mod the result with 7.
temp = days % 365 days = temp % 7