我的类(class)有作业:
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.
这是我编写的代码:
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);
}
}
当我用 YYY\MM\DD 初始化
date
时,在检查 dayOfTheWeek 的近期日期时一切正常,但当我输入我的出生日期 (1991\11\14) 时,它星期三回来,但我星期四出生。当我尝试获取日期和月份来检查十二生肖时,它完全崩溃了,当我输入 11 时返回 0(对于月份,日期效果很好)。
更重要的是...当我开始使用
+1
进行搜索时,即使differenceInDaysFrom
也停止正常工作
最佳答案
对于您的生日问题(周三或周四):
首先,您必须将 0=January
以来的第 10 个月作为 11 月。其他答案已经发现了这一点。
那么你需要将你的字符串数组声明为:
new String[] { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday" };
因为,DAY_OF_WEEK,1=Sunday,2=MONDAY,
检查Calendar类的javaDoc。那么你应该得到“星期四”
对于生肖法。您输入了 11,因此您的日期对象收到的月份参数为 11+1=12。 12 不是有效月份(0-11 有效,如上所述,Jan=0)因此您感到害怕。 :)
关于java - 获取正确的星期几和月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13921734/