简体   繁体   中英

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.

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

Use the following code:

Calendar mCalendar  = new GregorianCalendar(year, month, day);
mCalendar.add(Calendar.DAY_OF_YEAR, 1);
Date mDate          = mCalendar.getTime();

start of by initializing you calendar, add mCalendar.add(Calendar.DAY_OF_YEAR, 1); or substract mCalendar.add(Calendar.DAY_OF_YEAR, -1); a day, get the current date, then format it to your needs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM