Design a program to accept a day number (between 1 and 366), year (in 4 digits) from the user to generate and display the corresponding date. Also, accept āNā (1 <= N <= 100) from the user to compute and display the future date corresponding to āNā days after the generated date. Display an error message if the value of the day number, year and N are not within the limit or not according to the condition specified.
import java.util.*;
public class NumberToDate {
int days, year, after;
private String[] MONTH_NAME = {
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October",
"November", "December"
};
void input() {
Scanner sc = new Scanner(System.in);
System.out.print("Day Number: ");
days = sc.nextInt();
System.out.print("Year: ");
year = sc.nextInt();
if (year < 1000 || year > 9999) {
System.out.println("Year should 4 digit number");
System.exit(0);
}
System.out.print("Date After(in days): ");
after = sc.nextInt();
if (after < 1 || after > 100) {
System.out.println("Date After should be between 1 and 100");
System.exit(0);
}
sc.close();
}
private String postfix(int n) {
int r = n % 10;
if (r == 1 && n != 11)
return "st";
else if (r == 2 && n != 12)
return "nd";
else if (r == 3 && n != 13)
return "rd";
else
return "th";
}
private String date_convert(int n, int y) {
int max = 365, m = 1, d = 0;
int[] DAY_COUNT = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (y % 4 == 0) {
max++;
DAY_COUNT[1]++;
}
while (n > max) {
n -= max;
y++;
}
while (true) {
int m_days = DAY_COUNT[m - 1];
d = n % (m_days + 1);
n -= m_days;
if (n > 0) {
m++;
} else
break;
}
return String.format("%d%s %s, %d", d, postfix(d), MONTH_NAME[m - 1], y);
}
void showDate() {
System.out.println("Date: " + date_convert(days, year));
}
void showAfterDate() {
System.out.printf("Date After %d Days: %s\n", after, date_convert(days + after, year));
}
public static void main(String[] args) {
NumberToDate a = new NumberToDate();
a.input();
a.showDate();
a.showAfterDate();
}
}
Name | Type | Description |
---|---|---|
global | ||
days | int | Stores the day number |
year | int | Stores the year |
after | int | Stores the number of days after the given date |
MONTH_NAME | String[] | Stores the name of each month |
void input() | ||
sc | Scanner | Used to take input |
private String postfix(int n) | ||
r | int | stores the last digit of n |
private String date_convert(int n, int y) | ||
max | int | Stores the number of days in the given year |
m | int | Stores the month number |
d | int | Stores the day number |
DAY_COUNT | int[] | Stores the number of days in each month |
n | int | Stores the day number provided in the argument |
y | int | Stores the year provided in the argument |
m_days | int | Stores the number of days in the current month |
void main() | ||
a | NumberToDate | Object of the class NumberToDate to invoke its methods |