Today, in Europe, the date is 1 October 2015. Can you tell me why running this code displays the date as 31 Oct 2015?
Calendar yesterday = Calendar.getInstance();
yesterday.roll(Calendar.DATE, false);
System.out.println(yesterday.getTime());
Calendar.DATE
represents the day of the month, not the day of the year. Thus, when rolling the day of the month backwards of 1 unit, we are essentially going from the 1st to the last day of the month.
Quoting the roll
Javadoc (emphasis mine):
Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields .
and quoting the Calendar
Javadoc:
A larger field represents a larger unit of time.
As such, fields like MONTH or YEAR are not changed by this method when rolling the day of the month.
You should use Calendar.DAY_OF_YEAR
instead:
Calendar yesterday = Calendar.getInstance();
yesterday.roll(Calendar.DAY_OF_YEAR, false);
System.out.println(yesterday.getTime());
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.