Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find which day of the week it is - Java [duplicate]

Tags:

java

date

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!

like image 358
Ethan Edwards Avatar asked Aug 20 '13 10:08

Ethan Edwards


People also ask

How do you calculate what day of the week a date is java?

To get the day of week for a particular date in Java, use the Calendar. DAY_OF_WEEK constant.

What is the use of calendar getInstance () in java?

The getInstance() method in Calendar class is used to get a calendar using the current time zone and locale of the system. Parameters: The method does not take any parameters. Return Value: The method returns the calendar.

What is Calendar Day_of_week in java?

DayOfWeek is an enum representing the 7 days of the week - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday. In addition to the textual enum name, each day-of-week has an int value. The int value follows the ISO-8601 standard, from 1 (Monday) to 7 (Sunday).


1 Answers

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.

like image 79
Dileep Avatar answered Oct 18 '22 21:10

Dileep