I created a layout with three Buttons
. My idea is to use these three buttons as a datepicker. Those three buttons are -
,Today
,+
.
If I press the today button displays today's date. When I press -
it displays yesterdays date. If I press +
it displays tomorrow's date. No problem. But it only works once. My requirement is to as long as I press -
it has to display previous day's dates i.e 19-Aug-2015
,18-Aug-2015
,17-Aug-2015
,etc., My code is
imgtoday.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
googleMap.clear();
Date date1=new Date(System.currentTimeMillis());
SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
String date=sdf.format(date1);
drawRoute(date);
imgHistory.setClickable(false);
imgHistory.setBackgroundResource(R.drawable.btn_disabled);
calculateDistance(date);
}
});
previousDay=(Button)findViewById(R.id.button9);
nextDay=(Button)findViewById(R.id.button11);
previousDay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
googleMap.clear();
Date date1=new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24));
SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
String date=sdf.format(date1);
drawRoute(date);
calculateDistance(date);
}
});
nextDay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
googleMap.clear();
Date date1=new Date(System.currentTimeMillis() + (1000 * 60 * 60 * 24));
SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
String date=sdf.format(date1);
drawRoute(date);
calculateDistance(date);
}
});
Anyone please help. Thanks.
Use Calendar:
Calendar cal = Calendar.getInstance();
cal.setTime(TODAY);
cal.add(Calendar.DAY_OF_MONTH, 1); //Adds a day
cal.add(Calendar.DAY_OF_MONTH, -1); //Goes to previous day
yourDate = cal.getTime();
Here is my code I have used for increment and decrement dates
/**
* Get next date from current selected date
*
* @param date date
*/
public Date incrementDateByOne(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, 1);
Date nextDate = c.getTime();
return nextDate;
}
/**
* Get previous date from current selected date
*
* @param date date
*/
public Date decrementDateByOne(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, -1);
Date previousDate = c.getTime();
return previousDate;
}
I hope it helps!
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