0

get next and the previous date of selected date or current date by clicking arrow left Right button like this image

image

Tanveer Hasan
  • 247
  • 2
  • 9
  • If you are using LocalDate then you can use `localDate.minusDays(1)` and `localDate.plusDays(1)` to get previous or next day. More about LocalDate here https://developer.android.com/reference/java/time/LocalDate available from api 26 if you target earlier devices you need to have desugaring enabled in project. – Per.J Dec 09 '21 at 08:10

2 Answers2

0
Calendar c = Calendar.getInstance();
//for selected date add this line c.set(2021,2,2)
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
textview.setText(formattedDate);

For next date

previous.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            c.add(Calendar.DATE, -1);
            formattedDate = df.format(c.getTime());
            textview.setText(formattedDate);
         }
      });

For previous date

next.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            c.add(Calendar.DATE, 1);
            formattedDate = df.format(c.getTime());
            textview.setText(formattedDate);
        }
    });
Tanveer Hasan
  • 247
  • 2
  • 9
0

Don't use old Calendar and SimpleDateForamt apis, it's outdated and troublesome

Use LocalDateTime to get the system date and time.

Current Date

val dateTime = LocalDateTime.now()   // current date
val formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)  // date time formatter
Log.d("Date:", "parssed date ${dateTime.format(formatter)}")

For Previous Date

button.setOnClickListener { 
        val previousDate = dateTime.minusDays(1)
        Log.d("Date:", "previous date ${previousDate.format(formatter)}")
}

For Next Date

button.setOnClickListener {
        val nextDate = dateTime.plusDays(1)
        Log.d("Date:", "next date ${nextDate.format(formatter)}")
}

Output:
Current date - Dec 9, 2021
Previous date - Dec 8, 2021
Next date - Dec 10, 2021

Note: LocalDateTime only works in android 8 and above, to use it below android 8 enable desugaring

Nitish
  • 3,075
  • 3
  • 13
  • 28