2

我去显示当前日期和最后六 (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));

但是我如何减少天数?

4

2 回答 2

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);                         
}                                                 
于 2012-11-02T13:02:16.780 回答
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()));

等等...

于 2012-11-02T13:02:46.680 回答