Android日历获取当前周,前几周和下周

时间:2017-05-19 03:32:21

标签: java android

我正在尝试检索本周的当前日期IE:Mon-Sun。然后我有两个按钮,Previous和Next,它们应该检索下一个和前几个星期的日期。这应该允许我无限期地轮换一年中的几周。

  1. 上周:2017/05 / 8-2017 / 05/14
  2. 装载周:2017/05 / 15-2017 / 05/21
  3. 下周:2017/05 / 22-2017 / 05/28
  4. 代码加载Mon-Sun的中间日期。当我点击下一个按钮时,它会带我到下一周的下一组天。当我从这里点击Previous时,它会跳过初始加载的周并跳转到下周的日期。当我使用Previous to Next进行另一种方式时也会发生同样的情况。当我继续按下下一个和上一个按钮时,他们不会继续加载新周。

    我做错了什么?

    初始加载代码:

    DateFormat format = new SimpleDateFormat("M-dd");
    Calendar calendar = Calendar.getInstance();
    calendar.setFirstDayOfWeek(Calendar.MONDAY);
    calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    calendar.add(Calendar.DAY_OF_MONTH, 7);
    
    days = new String[7];
    
    for (int i = 0; i < 7; i++)
    {
        days[i] = format.format(calendar.getTime());
        calendar.add(Calendar.DAY_OF_MONTH, 1);
    }
    

    下周代码:

    DateFormat format = new SimpleDateFormat("M-dd");
    Calendar calendar = Calendar.getInstance();
    calendar.setFirstDayOfWeek(Calendar.MONDAY);
    calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    calendar.add(Calendar.DAY_OF_MONTH, -7);
    
    days = new String[7];
    
    for (int i = 0; i < 7; i++)
    {
        days[i] = format.format(calendar.getTime());
        calendar.add(Calendar.DAY_OF_MONTH, 1);
    }
    

    上周代码:

    Calendar calendar; // Stick this at the start of your code

    解决方案:

    DateFormat format = new SimpleDateFormat("M-dd"); calendar = Calendar.getInstance(); calendar.setFirstDayOfWeek(Calendar.MONDAY); calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); days = new String[7]; for (int i = 0; i < 7; i++) { days[i] = format.format(calendar.getTime()); calendar.add(Calendar.DAY_OF_MONTH, 1); }

    初始加载代码:

    DateFormat format = new SimpleDateFormat("M-dd");
    calendar.setFirstDayOfWeek(Calendar.MONDAY);
    calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    calendar.add(Calendar.DAY_OF_MONTH, 7);
    
    days = new String[7];
    
    for (int i = 0; i < 7; i++)
    {
        days[i] = format.format(calendar.getTime());
        calendar.add(Calendar.DAY_OF_MONTH, 1);
    }
    

    下周代码:

    DateFormat format = new SimpleDateFormat("M-dd");
    calendar.setFirstDayOfWeek(Calendar.MONDAY);
    calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    calendar.add(Calendar.DAY_OF_MONTH, -7);
    
    days = new String[7];
    
    for (int i = 0; i < 7; i++)
    {
        days[i] = format.format(calendar.getTime());
        calendar.add(Calendar.DAY_OF_MONTH, 1);
    }
    

    上周代码:

    {{1}}

1 个答案:

答案 0 :(得分:0)

我想通过调用:Calendar calendar = Calendar.getInstance();每次都让日历混乱。

解决方法是删除Calendar calendar = Calendar.getInstance();从前一个和下一个代码实现变量Calander日历;在代码的开头。我将使用解决方案编辑原始代码。