在使用Calendar的时候,往往因为国外和中国的习惯不同,而造成迥异。比如,老外习惯周日作为每周的起始第一天,而中国习惯用周一作为每周的起始第一天。
我看见Calendar的API里面有 setFirstDayOfWeek()。
所以我设置setFirstDayOfWeek(Calendar.MONDAY)
但是发现使用cal.get(Calendar.DAY_OF_WEEK)得到的,还是以周日为起始第一天的结果。很是郁闷。上网找了,老外也有遇到这个问题的。老外遇到的问题:
- Calendar myCalendar = Calendar.getInstance();
- myCalendar.setTime(new Date());
- System.out.println(myCalendar.get(Calendar.DAY_OF_WEEK);
- myCalendar.setFirstDayOfWeek(Calendar.MONDAY);
- System.out.println(myCalendar.get(Calendar.DAY_OF_WEEK);
Calendar returns the same value before and after setFirstDayOfWeek.
Any ideas on why this doesn't work and how to get it to work?
Any ideas on why this doesn't work and how to get it to work?
另一个老外给出了结论,才让我恍然大悟:
This is one of many ways in which
java.util.Calendar
is counterintuitive. It does work, but not the way you're expecting. Look at the documentation[ for the
DAY_OF_WEEK
field: "This field takes values SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY." When your program prints 6, it's telling you that the day of week is
FRIDAY
. This constant value has nothing to do with the beginning of the week - it's just a constant that means FRIDAY. It does coincidentally happen to be the same as the day of the week if the first day of the week is SUNDAY (1) - but it doesn't change if the first day of the week is redefined.
Compare this to the API for WEEK_OF_MONTH and WEEK_OF_YEAR , which do say that they depend on the first day of the week. You can test to see if this works correctly for your purposes.
If you really need a number representing day of week with 1 meaning Monday and 7 meaning Sunday, you can get it with a tiny bit of math:
Compare this to the API for WEEK_OF_MONTH and WEEK_OF_YEAR , which do say that they depend on the first day of the week. You can test to see if this works correctly for your purposes.
If you really need a number representing day of week with 1 meaning Monday and 7 meaning Sunday, you can get it with a tiny bit of math:
- int dayOfWeek = myCalendar.get(Calendar.DAY_OF_WEEK) - 1;
- if (dayOfWeek == 0)
- dayOfWeek = 7;
看完了,就明白了。
public int getDayOfWeek(String dateString){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = format.parse(dateString);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.setFirstDayOfWeek(Calendar.MONDAY);
int tmp = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (0 == tmp) {
tmp = 7;
}
return tmp;
} catch (ParseException e) {
e.printStackTrace();
return -1;
}
}