How to get the next date when click on button in android?
Solution 1
You could use the Calendar
to get the current date
. And then if you want the previous date
you could use c.add(Calendar.DATE, -1)
where -1
is the number of days you want to decrement from current date
. In your case we want the previous date
so used -1
.Similarly, to get the next date
use c.add(Calendar.DATE, 1)
. You can get the number of days previous or before just by altering the integer.
First of all to set current date to textview.
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
textview.setText(formattedDate);
Then on previous button click:
previous.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
c.add(Calendar.DATE, -1);
formattedDate = df.format(c.getTime());
Log.v("PREVIOUS DATE : ", formattedDate);
textview.setText(formattedDate);
}
});
On Next Button click:
next.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
c.add(Calendar.DATE, 1);
formattedDate = df.format(c.getTime());
Log.v("NEXT DATE : ", formattedDate);
textview.setText(formattedDate);
}
});
Solution 2
Try this,
private static SimpleDateFormat dateFormat = new SimpleDateFormat("dd -MM-yyyy", Locale.US);
int dayShift = n; // Positive for next days, negative for previous days
Calendar c = Calendar.getInstance();
if (dayShift != 0) {
c.add(Calendar.DAY_OF_YEAR, dayShift);
}
mdate.setText(dateFormat.format(c.getTime());
user2681425
Updated on June 30, 2022Comments
-
user2681425 almost 2 years
In my application i have a text view to set the current date and two buttons for next date and previous date.
When click on next button i need to set the next date to text view without opening the date picker and similarly to previous button also.
Please can any one help me.
-
user2681425 over 10 yearsThanks for giving answer.
-
user2681425 over 10 yearsThanks for giving answer.
-
Hariharan over 10 years@user2681425 if it had helped you, atleast you could vote up!
-
user2681425 over 10 yearsThanks for giving answer.
-
Saad Bilal over 9 yearsWhat if Date is not current date then how can we tackle this to and fro of date, kindly help ?
-
Shirish Herwade about 9 years@SaadBilal hi, I want the same that you mentioned here, I want previous date of a particular date, but not today's date. Did you find any solution?
-
Saad Bilal about 9 years@Shirish: Yes this is very easy, only you have to use calendar.set("any date") method to set any date and then you can use above logic.