Reputation: 13
I just want to subtract 1 day from New year date in my current scenario.
But while I subtract I get date: 31-0-2100
.
Calendar cal = Calendar.getInstance();
cal.set(2100, 1, 1);
cal.add(Calendar.DATE, -1);
String dateStr = ""+cal.get(Calendar.DATE)+
"-"+cal.get(Calendar.MONTH)+"-"+cal.get(Calendar.YEAR);
System.out.println(dateStr);
The actual date should be: 31-12-2099
Upvotes: 0
Views: 572
Reputation: 13736
Implemented using Calendar functionality.
Tested and Executed
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
cal.set(2099, 00, 01);
cal.add(Calendar.DATE, -1);
System.out.println(dateFormat.format(cal.getTime()));
Another solution Formulate the DateTime using the below methods
date.getYear();
date.getDay();
date.getMonth();
Try to pass those arguments into the DateTime.
DateTime date = new DateTime(2100, 1, 1, 0, 0, 0);
date = date.minusDays(1);
System.out.println(date.toString("yyyy-MM-dd"));
Upvotes: 0
Reputation: 93872
When you're doing cal.set(2100, 1, 1);
, the date you set is actually the first day of February and not January since months are 0 base indexed (0 -> January, ..., 11 -> December
).
I would recommend you to use JodaTime which is a far better library to deal with dates and time.
DateTime date = new DateTime(2100, 1, 1, 0, 0, 0);
date = date.minusDays(1);
System.out.println(date.toString("dd-MM-yyyy")); //31-12-2099
Or if you're using java-8, they introduced a brand-new date and time API:
LocalDate date = LocalDate.of(2100, Month.JANUARY, 1);
date = date.minusDays(1);
System.out.println(date.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))); //31-12-2099
Upvotes: 3
Reputation: 23035
Notice that the field MONTH is 0-indexed, so the month '1' is actually February and what you are getting: '31-0'2100' is the last day of January.
Source: http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#MONTH
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.
Upvotes: 1
Reputation: 444
In java the month 0 is January.
So what you got is correct since you're substracting 1 day from February 1st 2100
Upvotes: 1