Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the next date when click on button in android?

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.

like image 263
user2681425 Avatar asked Dec 14 '13 11:12

user2681425


2 Answers

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);
            }
});
like image 141
Hariharan Avatar answered Sep 21 '22 02:09

Hariharan


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());
like image 28
No_Rulz Avatar answered Sep 20 '22 02:09

No_Rulz