Search code examples
javaandroiddatecalendarsimpledateformat

android get previous date of a corresponding date(not yesterday's date)


Please read question carefully before marking duplicate.

I want previous date of a corresponding date.(Not yesterday's date)

e.g. If user click button once he will be navigated to another screen and is shown data regarding yesterday.

And if he clicks again the same button on that screen, then data should be shown on day before yesterday....and so on... till data present in my database.

So I want to get previous date of a corresponding date. i.e. if I have date 31 Jan 2014(I'm using format 31012014 to store in db) then i should get date 30012014.

I know how to get yesterday's date e.g. below code

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, -1);
    DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy", Locale.getDefault());
    String yesterdayAsString = dateFormat.format(calendar.getTime());

which gives dates compared to today but I want previous date compared to some other valid date.

So how to get that.


Solution

  • You have to use SimpleDateFormat to convert String > Date, after Date > Calendar, for instance;

    String sDate = "31012014";
    SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy", Locale.getDefault());
    Date date = dateFormat.parse(sDate);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.DATE, -1);
    String yesterdayAsString = dateFormat.format(calendar.getTime());