Home > Net >  How to get next and previous date of selected date or current date by clicking arrow left Right
How to get next and previous date of selected date or current date by clicking arrow left Right

Time:12-09

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

image

CodePudding user response:

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

CodePudding user response:

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

  • Related