如何显示最后六个日期,java.util.Date?

时间:2012-11-02 12:58:05

标签: java date

我去显示当前日期和六(6)个最后日期

示例:

02/11/2012
01/11/2012
31/10/2012
30/10/2012
29/10/2012
28/10/2012

在我使用的JAVA中获取当天:

Date date = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
System.out.println("current day : "+sdf.format(date));

但我如何减少日子?

2 个答案:

答案 0 :(得分:4)

您可以使用Calendar#add方法减去一天,例如:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Calendar cal = Calendar.getInstance();
Date date=cal.getTime();
System.out.println(sdf.format(date)); //remove line to display only the last 5 days 
for (int i=0;i<5;i++){
   cal.add(Calendar.DAY_OF_MONTH,-1);
   date=cal.getTime();
   System.out.println(sdf.format(date));
}

像Jon Skeet(很快500k :) :)建议,我也发现Joda Time API更清洁和恰当,即使对于这么简单的任务:

DateTime dt = new DateTime();                     
for (int i = 0; i < 6; i++) {                     
    System.out.println(dt.toString("yyyy/MM/dd"));
    dt = dt.minusDays(1);                         
}                                                 

答案 1 :(得分:2)

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
System.out.println("current day : "+sdf.format(c.getTime()));

// decrement 1 day
c.add(Calendar.DAY_OF_MONTH, -1);

// getTime() returns a java.util.Date
System.out.println("the day before : "+sdf.format(c.getTime()));

// getTimeInMillis() returns a long, which can be used to construct a java.sql.Date
System.out.println("the day before : "+sdf.format(new java.sql.Date(c.getTimeInMillis()));

等等......