2

In a scenario i want to roll back one day from current time.It works fine when i use the function Calendar.roll() , but when it comes to 2014-1-1 00:00 it appears to be an unexpected result. here's the code:

Calendar c = Calendar.getInstance();
try {
     c.setTimeInMillis(sdf.parse("2014-1-1 00:00").getTime());
 } catch (ParseException e) {
    e.printStackTrace();
 }
 c.roll(Calendar.DAY_OF_YEAR, -1);
 c1.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), 0, 0, 0);

System.out.println(sdf.format(c1.getTime()));

the result is: 2014-12-31 00:00

if i use Calendar.DAY_OF_MONTH instead of DAY_OF_YEAR, the result would be 2014-01-31 00:00

does anyone have a solution when rolling back one day also rolls back the year, for this example, change 2014 to 2013?

user3236929
  • 123
  • 1
  • 2
  • 7

2 Answers2

3

as per the javadocs http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

Roll rule. Larger fields are unchanged after the call.

so use

c.add(Calendar.DAY_OF_YEAR, -1)
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

Try using the add method instead.

c.add(Calendar.DAY_OF_YEAR, -1);
JamesH
  • 279
  • 2
  • 6