2016-12-27 123 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(); 
    } 
}