This is a very common question which is usually asked for 2-3 years experience guys to find the day of a week if a given date is given? Lets suppose if i give 3rd March, 2014, the program should output me the day of the week whether that day was Saturday or Wednesday?
This algorithm is solved by using Sakamotos algorithm which is a very famous algo for calculating the day of the week for a given date!
For more info about this algorithm you can find it here:-
http://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week
The following code helps us in finding the exact day of the week for any date:-
package com.pack;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DayOfWeek {
private static int dayofweek(int d, int m, int y)
{
int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
boolean b=m<3;
if(b){
y=y-1;
}
return ( y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
}
public static void main(String[] args) {
int day = dayofweek(31, 3, 2015);
System.out.println(day);
}
}
This will return me the exact day of the week for a given date.
Here, we have declared an array t which contains values which are derived from Sakamotos algorithm.
These values are used to compute a formula and we are passing Date, Month and year as inputs to the method dayofweek().
This algorithm is solved by using Sakamotos algorithm which is a very famous algo for calculating the day of the week for a given date!
For more info about this algorithm you can find it here:-
http://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week
The following code helps us in finding the exact day of the week for any date:-
package com.pack;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DayOfWeek {
private static int dayofweek(int d, int m, int y)
{
int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
boolean b=m<3;
if(b){
y=y-1;
}
return ( y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
}
public static void main(String[] args) {
int day = dayofweek(31, 3, 2015);
System.out.println(day);
}
}
This will return me the exact day of the week for a given date.
Here, we have declared an array t which contains values which are derived from Sakamotos algorithm.
These values are used to compute a formula and we are passing Date, Month and year as inputs to the method dayofweek().
No comments:
Post a Comment