0

I have an android app who manipulates dates via java.util.Calendar

When I want to use today's date, I use :

 Date today = Calendar.getInstance().getTime();

I want to know how to manipulate yesterday's date, I've tried multiple syntax but nothing worked, I was thinking about something like

yesterday = today - 24(UNITS.HOURS)

but that's not correct !

Shweta Chauhan
  • 6,739
  • 6
  • 37
  • 57
M.garcia
  • 41
  • 1
  • 8
  • 1
    So you just took a wild guess of what you could do instead of doing research? http://idownvotedbecau.se/noresearch/ – f1sh Mar 28 '19 at 09:51
  • As an aside consider throwing away the long outmoded and poorly designed `Calendar` and `Date`, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. `LocalDate.now(yourTimeZone).minusDays(1)`. – Ole V.V. Mar 28 '19 at 10:00
  • There’s [a good answer here](https://stackoverflow.com/a/33893147/5772882) (it does a little more than you asked for, just take the part that you need). – Ole V.V. Mar 28 '19 at 10:06

2 Answers2

1

Try this :

using this code you will get yesterday date always.

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
dateFormat.format(cal.getTime());
Abhinav Gupta
  • 2,225
  • 1
  • 14
  • 30
0

You can try like this:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, (cal.get(Calendar.DAY_OF_MONTH) - 1));
Date yesterDayDate = cal.getTime();
Rumit Patel
  • 8,830
  • 18
  • 51
  • 70