Unsure what get(Calendar.DAY_OF_WEEK) returns

让人想犯罪 __ 提交于 2019-12-14 03:44:38

问题


My problem can be easily created by the scenario below:

 //create a gregorian calendar object that set the date and time as 4th June 2012 at 10:30PM
 Calendar calendar = new GregorianCalendar(2012, 6, 4, 22, 30);

 //when I print out these:
 System.out.println(calendar.get(Calendar.DAY_OF_WEEK));
 System.out.println(calendar.get(Calendar.MINUTE));
 System.out.println(calendar.get(Calendar.HOUR));
 System.out.println(calendar.get(Calendar.DATE));
 System.out.println(calendar.get(Calendar.MONTH));
 System.out.println(calendar.get(Calendar.YEAR));

 //output reads as:
 4
 30
 10
 4
 6
 2012

 //so does calendar.get(Calendar.DAY_OF_WEEK) == calendar.get(Calendar.DATE) ???

Just so that everyone is clear the 4th of June 2012 is a Monday, so shouldn't calendar.get(Calendar.DAY_OF_WEEK) return 0 as part of the first day of the week?

Thank for your all your help and concerns, please also verify the source that you are referring to.

user1442080


回答1:


The month in java Calendar classes is 0-based. So June is month number 5.

You actually created an object representing July 4th, which happens to be a Wednesday, which is the fourth day of that week.




回答2:


One should always look for values returned by Calendar.{field} e.g. like Calendar.SUNDAY, Calendar.MONDAY, Calendar.JANUARY, Calendar.MARCH etc. and so on. This is because, the values returned by Calendar.{field} depends upon the TimeZone specified while creating Calendar instance. You can try this by creating two calendar instances with different timezones:

Calendar.getInstance("BST")

and

Calendar.getInstance() // default timezone

and now try getting calendar.get(Calendar.DAY_OF_WEEK) which will return different integer values for these two instances.



来源:https://stackoverflow.com/questions/10931152/unsure-what-getcalendar-day-of-week-returns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!