Today's challenge
Wap in JAVA to accept a given date, the program will return with the day falling on the given date without using array and fiction.
example...
if u enter today's date...i.e. 31 oct 2020
it will return Saturday
Answers
Answer:
String input_date="01/08/2012"; SimpleDateFormat format1=new SimpleDateFormat("dd/MM/yyyy"); Date dt1=format1. parse(input_date); DateFormat format2=new SimpleDateFormat("EEEE"); String finalDay=format2. format(dt1); Use this code for find the Day name from a input date.
Challenge Accepted.
Question:-
Write a program in Java to accept a given date, the program will return with the day falling on the given date without using array.
Program:-
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the date: ");
int K=sc.nextInt();
System.out.print("Enter the month: ");
int M=sc.nextInt();
System.out.print("Enter the year: ");
int y=sc.nextInt();
if(M>0&&M<3)
y--;
int D=y%100;
int C=y/100;
M-=2;
if(M==0)
M=12;
else if(M==-1)
M=11;
int F;
F=K+((13*M-1)/5)+D+(D/4)+(C/4) -(2*C);
F=F%7;
String x="";
switch(F)
{
case 1: x="Monday";
break;
case 2: x="Tuesday";
break;
case 3: x="Wednesday";
break;
case 4: x="Thursday";
break;
case 5: x="Friday";
break;
case 6: x="Saturday";
break;
case 0: x="Sunday";
break;
}
System.out.println("Its "+x+".");
}
}
How to solve?
This is solved by using zellers rule.
Zellers rule has only 1 formula which calculates the day on which the given date is falling.
Consider a date, say 06/08/1990
Here is the calculation part.
This is the required formula.
F = K + [(13xM – 1)/5] + D + [D/4] + [C/4] – 2C
where,
1) K = Date. (here, K=06)
In Zellers rule, months start from March.
2) M = Month no.
Remember that month Starts from March. So,
March = 1,
April = 2,
May = 3
.
.
.
.
Dec = 10,
Jan = 11
Feb. = 12
So, for 06/08/1990, M=6
3) D = Last two digits of the year
So, in our example of 6/08/1990 D=90
Remember that when you have to find day of the first or second month of any year, then Year=Given year-1
i.e. When you want to find Day of 15-2-1990.,
K=15,
Month=12,
D=Given Year-1=1990-1=1989=89
4) C = The first two digits of century
Here, C = 19.
Now, using the formula, we will calculate.
The formula is F = K + [(13xM – 1)/5] + D + [D/4] + [C/4] – 2C
Replacing the values in the formula, we get
F = 06 + [{(13 x 6)- 1}/5] + 90 + 90/4 + 19/4 – (2 x 19)
Therefore,
F = 06 + 77/5 + 90 + 90/4 + 19/4 – 38
Remember:- We have to calculate the integer part only.
F =06 + 15.4 + 90 + 22.5 + 4.75 – 38
>> F =06 + 15 + 90 + 22 + 4 – 38
Therefore, F = 99
Now, divide F by 7 and get the remainder.
These are the days. Put the values and find them.
1 = Monday
2 = Tuesday
3 = Wednesday
4 = Thursday
5 = Friday
6 = Saturday
0 = Sunday
Here, 1 represents Monday.
So by Zeller’s rule, 6th of August, 1990 was on a Monday.
In this way, the problem is solved.