简体   繁体   中英

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

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

图片

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

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

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