Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 649
Shirish Herwade Avatar asked Mar 31 '15 12:03

Shirish Herwade


2 Answers

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());
like image 163
LaurentY Avatar answered Oct 21 '22 06:10

LaurentY


Use this, Its working and tested code.

private String getPreviousDate(String inputDate){
                inputDate = "15-12-2015"; // for example 
                SimpleDateFormat  format = new SimpleDateFormat("dd-MM-yyyy");  
                try {  
                    Date date = format.parse(inputDate); 
                    Calendar c = Calendar.getInstance();
                    c.setTime(date);

                    c.add(Calendar.DATE, -1);
                    inputDate = format.format(c.getTime());
                    Log.d("asd", "selected date : "+inputDate);

                    System.out.println(date);  
                } catch (Exception e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                      inputDate ="";
                }
                return inputDate;
            }
like image 42
Yogendra Avatar answered Oct 21 '22 08:10

Yogendra