简体   繁体   中英

Java Date/Calendar oddness

I have a bit of (Java) that I where I am trying to simply subtract 7 days from the current date. It seemed to me like Calendar.add(..) should be the method to use (and what previous questions here seem to say), so that's what I tried:

SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
System.out.println("ReportUtil.getDefaultReportStartDate cal: "+cal.toString() );
System.out.println("PRE ReportUtil.getDefaultReportStartDate: "+df.format(cal.getTime()) );
cal.add(Calendar.DATE, -7);
System.out.println("POST ReportUtil.getDefaultReportStartDate: "+df.format(cal.getTime()) );

That looks ok to me but you'll see from the output below the month field seems to go a bit... sideways! The day of the month/date seems to change correctly, but what is going on with the month?!

ReportUtil.getDefaultReportStartDate cal: java.util.GregorianCalendar[time=1330098699960,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GB-Eire",offset=0,dstSavings=3600000,useDaylight=true,transitions=242,lastRule=java.util.SimpleTimeZone[id=GB-Eire,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2012,MONTH=1,WEEK_OF_YEAR=8,WEEK_OF_MONTH=4,DAY_OF_MONTH=24,DAY_OF_YEAR=55,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=3,HOUR_OF_DAY=15,MINUTE=51,SECOND=39,MILLISECOND=960,ZONE_OFFSET=0,DST_OFFSET=0]

PRE ReportUtil.getDefaultReportStartDate: 24-51-2012
POST ReportUtil.getDefaultReportStartDate: 17-51-2012

SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");

You get a strange month value because mm means minutes. Try:

 SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");

You can consult the whole list of the format symbols here: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

mm is the format string for Minute. You want MM

Your result seems to be correct.

The month is "1" in both dates of your first log line, which means February.

The "-mm-" in your SimpleDateFormat means minute and not month, thus the odd month of "51"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM