2012-09-15 26 views
2

獲取Calendar.MONTH瞭解年份,年份和星期幾,可以獲取月份的月份和月份的日期。例如如何從給定的WEEK_OF_YEAR,DAY_OF_WEEK,年份

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

謝謝

回答

1

這應該是

// +1 to the value of month returned, not to the value of MONTH constant. 
int monthGMT = aGMTCalendar.get(Calendar.MONTH) + 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()); 
+0

感謝您的答覆。雖然我試圖通過aGMTCalendar.setFirstDayOfWeek(Calendar.MONDAY)一週的第一天設置爲Monday(星期一應爲1),當我輸入dayOfWeekNum WEEKNUM = 6 38,我得到月/日= 9/14 –

+0

檢查我的答案。 –

+0

查看我的更新回答。 –

0

嘗試Calendar.SATURDAY常數而不是6字面值。

Calendar.SATURDAY其實76

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 
相關問題