2011-12-28 108 views
7

我希望獲得開始日期&結束日期爲一週的數字,以傳遞給方法的一週數。例如,如果我通過了週數爲51和一年2011,它應該回到我開始日期爲18 Dec 2011和結束日期爲24 Dec 2011從android的週數和年份中獲取星期的開始日期和結束日期

是否有任何的方法,這將有助於我實現這一目標?

+0

我試過使用MonthDisplayHelper&JodaTime,但不知何故無法達到要求。 Thanx Sunil&Chase ..會嘗試我們的解決方案,讓你知道 – AndroidGuy 2011-12-28 07:00:39

回答

19

您可以用下面的方法來獲得一個星期

void getStartEndOFWeek(int enterWeek, int enterYear){ 
//enterWeek is week number 
//enterYear is year 
     Calendar calendar = Calendar.getInstance(); 
     calendar.clear(); 
     calendar.set(Calendar.WEEK_OF_YEAR, enterWeek); 
     calendar.set(Calendar.YEAR, enterYear); 

     SimpleDateFormat formatter = new SimpleDateFormat("ddMMM yyyy"); // PST` 
     Date startDate = calendar.getTime(); 
     String startDateInStr = formatter.format(startDate); 
     System.out.println("...date..."+startDateInStr); 

     calendar.add(Calendar.DATE, 6); 
     Date enddate = calendar.getTime(); 
     String endDaString = formatter.format(enddate); 
     System.out.println("...date..."+endDaString); 
    } 
+0

2015年,2016年來一個星期多,但2013,2014來到正是...這是閏年的問題.. – 2013-01-29 12:41:44

+0

您好Kamal,任何解決方案以上提到的問題? – Deva 2015-12-28 09:21:00

3

您需要使用java.util.Calendar類的第一日期和結束日期。您可以使用public void set(int field, int value)方法將年份設置爲Calendar.YEAR,並將年份設置爲Calendar.WEEK_OF_YEAR

只要區域設置正確,您甚至可以使用setFirstDayOfWeek來更改一週的第一天。日曆實例表示的日期將成爲您的開始日期。只需爲您的結束日期添加6天。

Calendar calendar = new GregorianCalendar(); 
// Clear the calendar since the default is the current time 
calendar.clear(); 
// Directly set year and week of year 
calendar.set(Calendar.YEAR, 2011); 
calendar.set(Calendar.WEEK_OF_YEAR, 51); 
// Start date for the week 
Date startDate = calendar.getTime(); 
// Add 6 days to reach the last day of the current week 
calendar.add(Calendar.DAY_OF_YEAR, 6); 
// End date for the week 
Date endDate = calendar.getTime(); 
相關問題