-2

I want to select the previous day in a calendar. For example, if I have 02-28-2018 I need to set 27 automatically.

I have tried the below code but it fails when the date is 1st.

String currentDate = new SimpleDateFormat("dd").format(new Date());
int previousDay = Integer.parseInt(currentDate) - 1;
JeffC
  • 22,180
  • 5
  • 32
  • 55
Raa
  • 121
  • 2
  • 13

2 Answers2

3

There is an easy way to do this in Java 8

int previousDay = LocalDate.now().minusDays(1).getDayOfMonth();

For LocalDate Reference see here

Hope this Helps!

Arsen Davtyan
  • 1,891
  • 8
  • 23
  • 40
1

If using Java7 you can use Calendar

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -1);

System.out.println(new SimpleDateFormat("dd").format(cal.getTime()));

But for Java8 see http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html

Also a back-port for Java 6 & Java 7: ThreeTen-Backport.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64