2016-12-28 161 views
0

我有周數和年份,我想要得到星期的第一天和最後一天的日期,這是我的代碼,它給出我錯了結果,請告訴我我做錯了什麼。提前致謝。給周編號和年份找到星期的第一天和最後一天

SimpleDateFormat dt = new SimpleDateFormat("dd/mm/yyyy"); 
String start =""; 
String end =""; 
int week = 38; 
int yeat = 2016; 
Calendar calendar = Calendar.getInstance(); 
calendar.set(Calendar.WEEK_OF_YEAR, week); 
calendar.set(Calendar.YEAR, year); 
// firt day of week 
start = dt.format(calendar.getTime()); 
calendar.add(Calendar.DAY_OF_MONTH, 6); 
//last day of week 
end = dt.format(calendar.getTime()); 
+0

可能重複:如何計算在Java的ISO8601星期數日期(http://stackoverflow.com/q/25084576/642706) –

回答

1
  • 更正DateFormatter語法,一個月應該在死刑案件
  • 獲取週日和週六日起在特定的一週中, 一年過去了。

    SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy"); 
        String start =""; 
        String end =""; 
        int week = 38; 
        int year = 2016; 
        Calendar calendar = Calendar.getInstance(); 
        calendar.set(Calendar.YEAR, year); 
        calendar.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY); 
        calendar.set(Calendar.WEEK_OF_YEAR, week); 
         start = dt.format(calendar.getTime()); 
        calendar.set(Calendar.DAY_OF_WEEK,Calendar.SATURDAY); 
         end = dt.format(calendar.getTime()); 
        System.out.println(start+" |"+end); 
    
1

如果您使用Java 8+,你可以使用內置的週日期格式:

int week = 38; 
int year = 2016; 
String weekYear = year + "-W" + week + "-7"; //2016-W38-7 
LocalDate d = LocalDate.parse(year + "-W" + week + "-7", ISO_WEEK_DATE); //2016-09-25 

注:-7在字符串的結尾表示一週的最後一天(即星期日)。

0

試試這個:

SimpleDateFormat dt = new SimpleDateFormat("dd/mm/yyyy"); 
String start =""; 
String end =""; 
int week = 38; 
int year = 2016; 
Calendar calendar = Calendar.getInstance(); 
calendar.set(Calendar.WEEK_OF_YEAR, week); 
calendar.set(Calendar.YEAR, year); 

// firt day of week 
Calendar cal = calendar; 
while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) { 
    cal.add(Calendar.DATE, -1); 
} 
start = dt.format(cal.getTime()); 
System.out.println(start); 

Calendar cal1 = calendar; 
while (cal1.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY) { 
    cal1.add(Calendar.DATE, 1); 
} 
//last day of week 
end = dt.format(cal1.getTime()); 
System.out.println(end); 
相關問題