I have an assignment for my classes:
The class should have a methods of calculating the number of days between two dates, returns the day of the week and giving the sign of the zodiac for a given date.
And here is the code I've written:
import java.util.GregorianCalendar;
public class Data {
private GregorianCalendar date;
public Data(int year, int month, int day) {
date = new GregorianCalendar(year, month + 1, day);
}
public int differenceInDaysFrom(int year, int month, int day) {
GregorianCalendar tempDate = new GregorianCalendar(year, month, day);
int daysBetween = (int)(tempDate.getTimeInMillis()-date.getTimeInMillis())/(1000 * 60 * 60 * 24);
return Math.abs(daysBetween);
}
public String dayOfTheWeek() {
String[] stringDays = new String[]{ "Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday" };
return stringDays[date.get(GregorianCalendar.DAY_OF_WEEK) - 1];
}
public void zodiacSign() {
int day = date.get(GregorianCalendar.DATE);
int month = date.get(GregorianCalendar.MONTH);
System.out.println(day + " " + month);
}
}
When I initialize date
with YYY\MM\DD everything works perfect when checking dayOfTheWeek for the near-future dates but when I put my birth date (1991\11\14) it returns Wednesday but I was born on Thursday.
When I'm trying to get day and mont for checking the zodiac sign it totally freak out and returns 0 when I enter 11 (for month, days works good).
What is more... When I started wangling with +1
to month even differenceInDaysFrom
stopped working properly
for the problem of your birthday (wed or Thursday):
first you have to pass month 10 as Nov. since 0=January
. this has been spotted out by other answers.
then you need to declare your String array as:
new String[] { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday" };
because, DAY_OF_WEEK, 1=Sunday, 2=MONDAY,
check javaDoc of Calendar class. Then you should get "Thursday"
for the zodiac method. you entered 11, so your date object received month parameter is 11+1=12. 12 is not valid month (0-11 are valid, as mentioned above, Jan=0) Therefore you got freak out. :)