For Example I have the date: \"23/2/2010\" (23th Feb 2010). I want to pass it to a function which would return the day of week. How can I do this?
I
This works correctly...
java.time.LocalDate; //package related to time and date
It provides inbuilt method getDayOfWeek() to get the day of a particular week:
int t;
Scanner s = new Scanner(System.in);
t = s.nextInt();
s.nextLine();
while(t-->0) {
int d, m, y;
String ss = s.nextLine();
String []sss = ss.split(" ");
d=Integer.parseInt(sss[0]);
m = Integer.parseInt(sss[1]);
y = Integer.parseInt(sss[2]);
LocalDate l = LocalDate.of(y, m, d); //method to get the localdate instance
System.out.println(l.getDayOfWeek()); //this returns the enum DayOfWeek
To assign the value of enum l.getDayOfWeek()
to a string, you could probably use the method of Enum called name()
that returns the value of enum object.
Another "fun" way is to use Doomsday algorithm. It's a way longer method but it's also faster if you don't need to create a Calendar object with a given date.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
*
* @author alain.janinmanificat
*/
public class Doomsday {
public static HashMap<Integer, ArrayList<Integer>> anchorDaysMap = new HashMap<>();
public static HashMap<Integer, Integer> doomsdayDate = new HashMap<>();
public static String weekdays[] = new DateFormatSymbols(Locale.FRENCH).getWeekdays();
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws ParseException, ParseException {
// Map is fed manually but we can use this to calculate it : http://en.wikipedia.org/wiki/Doomsday_rule#Finding_a_century.27s_anchor_day
anchorDaysMap.put(Integer.valueOf(0), new ArrayList<Integer>() {
{
add(Integer.valueOf(1700));
add(Integer.valueOf(2100));
add(Integer.valueOf(2500));
}
});
anchorDaysMap.put(Integer.valueOf(2), new ArrayList<Integer>() {
{
add(Integer.valueOf(1600));
add(Integer.valueOf(2000));
add(Integer.valueOf(2400));
}
});
anchorDaysMap.put(Integer.valueOf(3), new ArrayList<Integer>() {
{
add(Integer.valueOf(1500));
add(Integer.valueOf(1900));
add(Integer.valueOf(2300));
}
});
anchorDaysMap.put(Integer.valueOf(5), new ArrayList<Integer>() {
{
add(Integer.valueOf(1800));
add(Integer.valueOf(2200));
add(Integer.valueOf(2600));
}
});
//Some reference date that always land on Doomsday
doomsdayDate.put(Integer.valueOf(1), Integer.valueOf(3));
doomsdayDate.put(Integer.valueOf(2), Integer.valueOf(14));
doomsdayDate.put(Integer.valueOf(3), Integer.valueOf(14));
doomsdayDate.put(Integer.valueOf(4), Integer.valueOf(4));
doomsdayDate.put(Integer.valueOf(5), Integer.valueOf(9));
doomsdayDate.put(Integer.valueOf(6), Integer.valueOf(6));
doomsdayDate.put(Integer.valueOf(7), Integer.valueOf(4));
doomsdayDate.put(Integer.valueOf(8), Integer.valueOf(8));
doomsdayDate.put(Integer.valueOf(9), Integer.valueOf(5));
doomsdayDate.put(Integer.valueOf(10), Integer.valueOf(10));
doomsdayDate.put(Integer.valueOf(11), Integer.valueOf(7));
doomsdayDate.put(Integer.valueOf(12), Integer.valueOf(12));
long time = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
//Get a random date
int year = 1583 + new Random().nextInt(500);
int month = 1 + new Random().nextInt(12);
int day = 1 + new Random().nextInt(7);
//Get anchor day and DoomsDay for current date
int twoDigitsYear = (year % 100);
int century = year - twoDigitsYear;
int adForCentury = getADCentury(century);
int dd = ((int) twoDigitsYear / 12) + twoDigitsYear % 12 + (int) ((twoDigitsYear % 12) / 4);
//Get the gap between current date and a reference DoomsDay date
int referenceDay = doomsdayDate.get(month);
int gap = (day - referenceDay) % 7;
int result = (gap + adForCentury + dd) % 7;
if(result<0){
result*=-1;
}
String dayDate= weekdays[(result + 1) % 8];
//System.out.println("day:" + dayDate);
}
System.out.println("time (ms) : " + (System.currentTimeMillis() - time)); //time (ms) : 80
time = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
Calendar c = Calendar.getInstance();
//I should have used random date here too, but it's already slower this way
c.setTime(new SimpleDateFormat("dd/MM/yyyy").parse("12/04/1861"));
// System.out.println(new SimpleDateFormat("EE").format(c.getTime()));
int result2 = c.get(Calendar.DAY_OF_WEEK);
// System.out.println("day idx :"+ result2);
}
System.out.println("time (ms) : " + (System.currentTimeMillis() - time)); //time (ms) : 884
}
public static int getADCentury(int century) {
for (Map.Entry<Integer, ArrayList<Integer>> entry : anchorDaysMap.entrySet()) {
if (entry.getValue().contains(Integer.valueOf(century))) {
return entry.getKey();
}
}
return 0;
}
}
Below is the two line of snippet using Java 1.8 Time API for your Requirement.
LocalDate localDate = LocalDate.of(Integer.valueOf(year),Integer.valueOf(month),Integer.valueOf(day));
String dayOfWeek = String.valueOf(localDate.getDayOfWeek());
LocalDate date=LocalDate.now();
System.out.println(date.getDayOfWeek());//prints THURSDAY
System.out.println(date.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.US) ); //prints Thu
java.time.DayOfWeek is a enum which returns the singleton instance for the day-of-week of the weekday of the date.
method below retrieves seven days and return short name of days in List Array in Kotlin though, you can just reformat then in Java format, just presenting idea how Calendar can return short name
private fun getDayDisplayName():List<String>{
val calendar = Calendar.getInstance()
val dates= mutableListOf<String>()
dates.clear()
val s= calendar.getDisplayName(DAY_OF_WEEK, SHORT, Locale.US)
dates.add(s)
for(i in 0..5){
calendar.roll( Calendar.DATE, -1)
dates.add(calendar.getDisplayName(DAY_OF_WEEK, SHORT, Locale.US))
}
return dates.toList()
}
out put results like
I/System.out: Wed
Tue
Mon
Sun
I/System.out: Sat
Fri
Thu
Can use the following code snippet for input like (day = "08", month = "05", year = "2015" and output will be "WEDNESDAY")
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day));
calendar.set(Calendar.MONTH, (Integer.parseInt(month)-1));
calendar.set(Calendar.YEAR, Integer.parseInt(year));
String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();