9

there has been a few other question which are pretty much the same, but i cant seem to get my bit of code to work. I get the user input which is there birthday dd/mm/yyyy. I'm ignoring leap years by the way. Im trying to determine what day of the week it was when the user was born. I have to determine how many days they were born from a certain date which in this case is Tuesday the 1st of January 1901. That's why ive done year-1901

day=int day;

used a switch to determine how many days in each month which is represented by dayMonth so July has 31, feb has 28 etc.

year=int year;

String[] days =
         {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
howManyDays = ((year-1901)*365 + dayMonth + day - 1);       
whatDay = (howManyDays%7);
days[whatDay]

It works sometimes, but then sometimes it doesn't. Any help is appreciated, if any questions feel free to ask. Thanks in advance and hope it makes sense!

5

2 Answers 2

18

You can use Java Calendar.

Calendar c = Calendar.getInstance();
c.set(year, month, day);

int day_of_week = c.get(Calendar.DAY_OF_WEEK);

This gives you an int which day of week it is, you can just provide an array to map with the "names" of the days.

3
  • Instead of c.set(2012, 03, 22); Can i go c.set(year, month, day) or something like that? Aug 20, 2013 at 11:02
  • sure :) it was just an example, i edited it to make it clear.
    – RedSonja
    Aug 20, 2013 at 11:47
  • FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle. Oct 1, 2018 at 0:47
7

The Code you have used cannot be implemented in any standard date operations because there are many cases like leap year etc.

Try to use java.util.Calendar for date operations that needs to know the details like Week Days, Months etc.

For Even More Complex date function Use JODA Calendar. Joda Calendar is fast and have a lot of operations like no of days between two days etc. You can Look into the above link for more details.

For Now you can use this

     Calendar calendar = Calendar.getInstance();
     calendar.set(year, month, date) ;
     int i=calendar.get(Calendar.DAY_OF_WEEK);

Here the value of i will be from 1-7 for Sunday to Saturday.

4
  • would the month be -1 of what ever it is? So if i wanted to enter july i would have to put 6? or would i put 7? Aug 20, 2013 at 11:48
  • @Dileep The link points to the google and may not work.
    – Roman C
    Aug 20, 2013 at 11:57
  • 2
    @EthanEdwards Month will be from 0-11, Week is from 1-7 for Sun- Sat
    – Dileep
    Aug 20, 2013 at 12:00
  • Dileep @RedSonja when I set calendar.set(2019, 9, 10) ; could you please help me why it returns 5 instead of 3. Sep 10 is Tuesday. Sep 10, 2019 at 15:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.