【问题标题】:I am passing index for dates and not expected dates coming我正在传递日期的索引,而不是预期的日期
【发布时间】:2022-01-04 05:56:04
【问题描述】:

在代码中,循环是让我下周 7 天并将它们添加到数组列表中。 当我尝试这个时,我得到周一、周二、周四、周日、周四、周二。我不明白为什么会这样。这不是一个正确的。

我需要输出周一、周二、网络、因此、周五、周六。

根据 docs here ,星期一的数值是 1,星期二是 2,依此类推。

   String dat,day;

    calendar = Calendar.getInstance();
    DateFormat sdf = new SimpleDateFormat("dd-MMM"); //Date and time

    DateFormat sdf_ = new SimpleDateFormat("EEE");
    Date date = new Date();


int i=0;

    while (i<7)
    {
         calendar.add(Calendar.DAY_OF_WEEK, i);
         dat = sdf.format(new Date(calendar.getTimeInMillis()));
         day = sdf_.format(new Date(calendar.getTimeInMillis()));

        mDate.add(dat);
        mDay.add(day);

         i++;

    }    
  
  

【问题讨论】:

  • 您在此处的每次迭代中都修改了相同的日历。如果您想这样做,它必须是calendar.add(Calendar.DAY_OF_WEEK, 1);.,您可以将日历设置为昨天以在循环中获取今天或使用类似calendar.add(Calendar.DAY_OF_WEEK, i*1)

标签: android date time days


【解决方案1】:

我认为您应该在 calendar.add(Calendar.DAY_OF_WEEK, 1) 中使用 1 而不是 i 因为您使用的是同一个日历实例。

int i=0;

    while (i<7)
    {
         calendar.add(Calendar.DAY_OF_WEEK, 1);
         dat = sdf.format(new Date(calendar.getTimeInMillis()));
         day = sdf_.format(new Date(calendar.getTimeInMillis()));

        mDate.add(dat);
        mDay.add(day);

         i++;

    }  

【讨论】:

    猜你喜欢
    • 2016-07-24
    • 1970-01-01
    • 2013-11-18
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多