1

我想显示当前日期和最近 5 天的日期

2013/04/24
2013/04/23
2013/04/22
2013/04/21
2013/04/20

我有如下代码..

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    Calendar cal = Calendar.getInstance();
    Date date=cal.getTime();
for (int i=0;i<5;i++){
                   cal.add(Calendar.DAY_OF_MONTH,-1);
                   date=cal.getTime();
                   String reportDate = sdf.format(date);
                   System.out.println("reportDate :" + reportDate);
}

在这里我得到如下输出..

reportDate :2013/04/23
reportDate :2013/04/22
reportDate :2013/04/21
reportDate :2013/04/20
reportDate :2013/04/19

但我想要最后五天的日期,包括当前日期......有人可以帮忙吗?

4

3 回答 3

1

试试这个!!

public static void getDate(){
    GregorianCalendar cal = new GregorianCalendar();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    int day = cal.get(GregorianCalendar.DAY_OF_MONTH);


        for(int i=day; i > (day-5); i--){
            cal.set(GregorianCalendar.DAY_OF_MONTH, i);

            Date date = cal.getTime();
            System.out.println(sdf.format(date));   
        }

}

v 2.0

public static void getDate1(){
    GregorianCalendar cal = new GregorianCalendar();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    cal.set(2013, 0, 1); // this is extreme case!!!

    int day = cal.get(GregorianCalendar.DAY_OF_MONTH);
    int month = cal.get(GregorianCalendar.MONTH);
    int year = cal.get(GregorianCalendar.YEAR);

        for(int i=day; i > (day-5); i--){
            cal.set(year, month, i);

            Date date = cal.getTime();
            System.out.println(sdf.format(date));   
        }

}

这是输出:

2013/01/01 2012/12/31 2012/12/30 2012/12/29 2012/12/28

于 2013-04-24T08:45:45.013 回答
0

i您在每次迭代中减去 的值。并i随着1每次迭代而增加。您可能只想减去1,而不管i.

cal.add(Calendar.DAY_OF_MONTH, -1);

编辑

或者甚至是更好的解决方案

cal.roll(Calendar.DAY_OF_MONTH, false);
于 2013-04-24T08:24:12.090 回答
0

问题是这一行:

cal.add(Calendar.DAY_OF_MONTH,-i);

具体-i部分。在第一次迭代i中,0您不会减去任何天数。接下来减去一天,得到第 23 天。接下来,减去两天,得到第 21 天,以此类推。

你想打印出初始日期,然后循环四次,每次迭代减去一天,所以:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String reportDate = sdf.format(date);
System.out.println("reportDate :" + reportDate);
for (int i = 0; i < 4; i++) {
    cal.add(Calendar.DAY_OF_MONTH, -1);
    date = cal.getTime();
    reportDate = sdf.format(date);
    System.out.println("reportDate :" + reportDate);
}
于 2013-04-24T08:24:28.210 回答