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.
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());
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With