2

知道年、年的周和周的日,就可以得到年的月和月的日。例如

 // 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

谢谢

4

4 回答 4

1

这应该是

// +1 to the value of month returned, not to the value of MONTH constant.
int monthGMT = aGMTCalendar.get(Calendar.MONTH) + 1;  
于 2012-09-15T18:53:45.470 回答
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());
于 2012-09-15T18:59:11.003 回答
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
于 2012-09-15T19:14:36.683 回答
0

尝试Calendar.SATURDAY常量而不是6文字。

Calendar.SATURDAY其实7不是6

于 2012-09-15T19:12:35.903 回答