简体   繁体   中英

Display 7 dates of current week in earlier Android

I'm using the java.time package of java to display week dates based on the current date in Android. I want Sunday through Saturday.

But the 'Time package link: ' was added from API 26. So, it is not supported for below API 26. So, I need an alternate solution for this. So that, I can run in below API 26.

Please provide me an alternate solution to display week dates based on the current date in Android.

So, it is not supported for below API 26.

You can use the java.time functionality in earlier Android. Use the back-port.

So, I need an alternate solution for this.

No, you don't.

Keep your code as-is. The back-port carries nearly the same API. So you'll need do little more than swap your import statements.

ThreeTen-Backport

Most of the java.time functionality is back-ported to Java 6 and Java 7 in the ThreeTen-Backport project.

This project is led by the same man, Stephen Colebourne, who leads the JSR 310 spec, the java.time implementation, and Joda-Time .

ThreeTenABP

The ThreeTen-Backport project is further adapted to Android specifically in the ThreeTenABP project.

Code

ZoneId z = ZoneId.systemDefault() ;  // Or ZoneId.of( "Africa/Tunis" )
LocalDate today = LocalDate.now( z ) ;

LocalDate localDate = today.with( org.threeten.bp.temporal.TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY ) ) ;
List< LocalDate > dates = new ArrayList<>( 7 ) ;
for( int i = 0 ; i < 7 ; i ++ ) {
    localDate = localDate.plusDays( i ) ;
    dates.add( localDate ) ;
}

Try something like this.

    int NUM_DAYS = 7; // You can get as many dates as you want.

    Calendar calendar = Calendar.getInstance();

    calendar.setFirstDayOfWeek(Calendar.SUNDAY); // The first day you want dates from.

    calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());

    for (int i=0; i < NUM_DAYS; i++){ 

        Date date = calendar.getTime();

        System.out.println(new SimpleDateFormat("EEEE dd/MM/yyyy").format(date));

        calendar.add(Calendar.DAY_OF_MONTH, 1);
    }

Here is two Calendar objects.

Calendar calendarCurrent = Calendar.getInstance();
calendarCurrent.getTime(); // To get current date-time.

Calendar calendarWeek = Calendar.getInstance();
calendarWeek.add(Calendar.DAY_OF_MONTH, 7);
calendarWeek.getTime(); // To get after 7 day's date-time.

If you want to display it in calendar-view then you can set maxDate as below.

calendarView.setMinDate(calendarCurrent.getTimeInMillis());
calendarView.setMaxDate(calendarWeek.getTimeInMillis());

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