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!

anubhava
  • 761,203
  • 64
  • 569
  • 643
Ethan Edwards
  • 119
  • 2
  • 3
  • 6

2 Answers2

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.

RedSonja
  • 350
  • 1
  • 13
  • Instead of `c.set(2012, 03, 22);` Can i go `c.set(year, month, day)` or something like that? – Ethan Edwards Aug 20 '13 at 11:02
  • sure :) it was just an example, i edited it to make it clear. – RedSonja Aug 20 '13 at 11:47
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Oct 01 '18 at 00: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.

Dileep
  • 5,362
  • 3
  • 22
  • 38