setFirstDayOfWeek in Calendar 不起作用,失效,不能用

在使用Calendar的时候,往往因为国外和中国的习惯不同,而造成迥异。比如,老外习惯周日作为每周的起始第一天,而中国习惯用周一作为每周的起始第一天。

我看见Calendar的API里面有 setFirstDayOfWeek()。

所以我设置setFirstDayOfWeek(Calendar.MONDAY)

但是发现使用cal.get(Calendar.DAY_OF_WEEK)得到的,还是以周日为起始第一天的结果。很是郁闷。上网找了,老外也有遇到这个问题的。老外遇到的问题:

 

 

  1.  Calendar myCalendar = Calendar.getInstance();  
  2.   myCalendar.setTime(new Date());  
  3.   System.out.println(myCalendar.get(Calendar.DAY_OF_WEEK);  
  4.   myCalendar.setFirstDayOfWeek(Calendar.MONDAY);  
  5.   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?

另一个老外给出了结论,才让我恍然大悟:

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:
  1. int dayOfWeek = myCalendar.get(Calendar.DAY_OF_WEEK) - 1;  
  2. if (dayOfWeek == 0)  
  3.     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;
	}
}
 


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值