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.
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);
}
});
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());
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