2016-12-27 76 views
-1

我有以下代碼:添加天日曆不工作在Android

public void createWeeks(JSONArray TargetDays){ 
    int helper, targetDayPos, curDayPos; 
    JSONArray dateContainer = new JSONArray(); 
    JSONArray dateData = new JSONArray(); 
    Calendar c = Calendar.getInstance(); 
    int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); 
    Utilities dayConverter = new Utilities(getApplicationContext()); 

    for(int i=0 ; i<TargetDays.length() ; i++){ 
     try { 
      targetDayPos = dayConverter.getDayPosition(TargetDays.getString(i)); 
      curDayPos = dayConverter.getCalenderDayPosition(dayOfWeek); 
      if (curDayPos > targetDayPos) { 
       helper = curDayPos - targetDayPos; 
       c.add(Calendar.DATE, -helper); 
      } 
      else if(targetDayPos > curDayPos){ 
       helper = targetDayPos - curDayPos; 
       c.add(Calendar.DATE, helper); 
      } 

      dateData.put(c.get(Calendar.YEAR)); 
      dateData.put(c.get(Calendar.MONTH)+1); 
      dateData.put(c.get(Calendar.DAY_OF_MONTH)+1); 
      Toast.makeText(getApplicationContext(),curDayPos+"\n"+targetDayPos,Toast.LENGTH_LONG).show(); 
      dateContainer.put(dateData); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 

    try { 
     weekDayList.put("days",TargetDays); 
     weekDayList.put("dates", dateContainer); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
} 

我創建在一個星期在這裏幾天的陣列和他們的日期。但增加日子不起作用,最後我只是獲得今天的日期。

+0

你能做出[最小,完整,可驗證的示例](http://stackoverflow.com/help/ mcve)?我相信這會對我們和你有很大的幫助。 –

+0

我需要關於「添加」日曆方法的幫助。它沒有做任何事情。什麼都沒發生。我添加了幾天後,然後我得到的時間它仍然是在添加之前的相同日期。 @Ole V.V. –

+0

我對'Calendar.add()'非常有信心。我懷疑你的問題在別的地方。你嘗試過調試器嗎? –

回答

0

我發現問題和@Ole V.V.在評論中說這不是關於日曆。 問題是關於它的算法。這是關於我創建json數組的方式。

我改成了這一點,並處理了它在我的程序以不同的方式:

public void createWeeks(JSONArray TargetDays){ 
    int helper, targetDayPos, curDayPos; 
    JSONArray dateContainer = new JSONArray(); 
    Date currentDate = new Date(); 
    Calendar c = Calendar.getInstance(); 
    int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); 
    Utilities dayConverter = new Utilities(getApplicationContext()); 

    try { 
     for(int i=0 ; i<TargetDays.length() ; i++){ 

      c.setTime(currentDate); 
      targetDayPos = dayConverter.getDayPosition(TargetDays.getString(i)); 
      curDayPos = dayConverter.getCalenderDayPosition(dayOfWeek); 
      if (curDayPos > targetDayPos) { 
       helper = curDayPos - targetDayPos; 
       c.add(Calendar.DATE, -helper); 
      } 
      else if(targetDayPos > curDayPos) { 
       helper = targetDayPos - curDayPos; 
       c.add(Calendar.DATE, helper); 
      } 
      dateContainer.put(dateFormat.format(c)); 

     } 
     weekDayList.put("days",TargetDays); 
     weekDayList.put("dates", dateContainer); 


    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
}