0

我正在使用以下代码显示一周中的所有日期,但是每当我选择一周的最后一个日期时,它就会打印下周的日期。为什么会发生这种情况?我的代码有什么问题吗?

/**Calendar week start on Monday**/
        
        Calendar selectedDate = Calendar.getInstance(Locale.US);        
        // Set current date to 21-april-2013
        selectedDate.set(selectedDate.get(Calendar.YEAR), selectedDate.get(Calendar.MONTH), 21);
        
        // create another instance of calendar      
        Calendar c = Calendar.getInstance(Locale.US);
        // set current date to this new calendar instance
        c = (Calendar) selectedDate.clone();
                
        // Set the calendar to monday of the current week   
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                
        // Print dates of the current week starting on Monday
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
        for (int i = 0; i < 7; i++) 
        {
            System.out.println(df.format(c.getTime()));
            c.add(Calendar.DATE, 1);
        }

输出显示日期从

22-april-2013 to 28-april-2013

但应该是

15-april-2013 to 21-april-2013
4

3 回答 3

0

您的代码在我的系统中运行良好

在此处输入图像描述

于 2013-04-22T09:22:17.997 回答
0

您将开始日期(即 4 月 21 日)添加天数。

for (int i = 0; i < 7; i++) 
{
    System.out.println(df.format(c.getTime()));
    c.add(Calendar.DATE, 1);
}

这可以解释为什么你的日期会在未来出现 =)

于 2013-04-22T09:18:03.377 回答
0

您将日期设置为 21,即星期日..

当你设置

c.setFirstDayOfWeek(Calendar.MONDAY);

它将变为 2013 年 4 月 15 日

所以,c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);明确设置为 15-april-13

于 2013-04-22T09:20:21.713 回答