了解年份,星期和星期几是否可以获得一年中的月份和一个月中的某一天。例如
// corresponding to September 15, 2012 if week starts on Monday
int weekNum = 38;
int dayNum = 6;
int year = 2012;
// set the calendar instance the a week of year and day in the future
Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
aGMTCalendar.setFirstDayOfWeek(Calendar.MONDAY);
aGMTCalendar.set(Calendar.WEEK_OF_YEAR,weekNum );
aGMTCalendar.set(Calendar.DAY_OF_WEEK,dayNum );
aGMTCalendar.set(Calendar.YEAR,year);
// get the month and day of month
int monthGMT = aGMTCalendar.get(Calendar.MONTH + 1); // returns 38 not 9
int dayOfMonthNumGMT = aGMTCalendar.get(Calendar.DAY_OF_MONTH);
// returns 14 but I wanted 15
谢谢
答案 0 :(得分:1)
这应该是
// +1 to the value of month returned, not to the value of MONTH constant.
int monthGMT = aGMTCalendar.get(Calendar.MONTH) + 1;
答案 1 :(得分:1)
获取monthGMT
的方式有类型。它应该是:
int monthGMT = aGMTCalendar.get(Calendar.MONTH) + 1;
在每次aGMTCalendar.set()
来电之后放下一行,您会看到在调用dayNum
之后,日期从15更改为14. aGMTCalendar.set(Calendar.DAY_OF_WEEK, dayNum)
忽略setFirstDayOfWeek
但是,在设置WEEK_OF_YEAR
时会考虑这一点。
System.out.println(aGMTCalendar.getTime());
答案 2 :(得分:0)
尝试Calendar.SATURDAY
常量而不是6
字面值。
Calendar.SATURDAY
实际上是7
而不是6
。
答案 3 :(得分:0)
// corresponding to September 15, 2012 if week starts on Monday
int weekNum = 38;
int dayNum = 6;
int year = 2012;
// set the calendar instance the a week of year and day in the future
Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
aGMTCalendar.setFirstDayOfWeek(Calendar.MONDAY);
aGMTCalendar.set(Calendar.WEEK_OF_YEAR,weekNum );
aGMTCalendar.set(Calendar.DAY_OF_WEEK,dayNum );
aGMTCalendar.set(Calendar.YEAR,year);
// get the month and day of month
int monthGMT = aGMTCalendar.get(Calendar.MONTH) + 1;
// should be 10
int dayOfMonthNumGMT = aGMTCalendar.get(Calendar.DAY_OF_MONTH) + 1;
// should be 15