Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

android - How to get previous 7 dates from a particular date in java?I am getting 7 dates from present date, but I want from particular date

//explain
public class DateLoop {
    static String finalDate; 
    static String particularDate;

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        SimpleDateFormat sdf = new SimpleDateFormat("d-M-yyyy ");
        Calendar cal = Calendar.getInstance();
        particularDate = "2-1-2018";
        // get starting date
        cal.add(Calendar.DAY_OF_YEAR, -7);

        // loop adding one day in each iteration
        for(int i = 0; i< 7; i++){
            cal.add(Calendar.DAY_OF_YEAR, 1);
            finalDate =sdf.format(cal.getTime());
            System.out.println(finalDate);
            //ie, its giving previous 7 dates from present date, but I want
            //particular date... thanks in advance
        }
    }

}

ie, its giving previous 7 dates from present date, but I want previous 7 dates from particular date.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

tl;dr

LocalDate.of( 2018 , Month.JANUARY , 23 )
         .minusDays( … )

java.time

You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

Use LocalDate for a date-only without time-of-day.

Using the Month enum.

LocalDate start = LocalDate.of( 2018 , Month.JANUARY , 23 ) ;  // 2018-01-23.

Using month numbers, 1-12 for January-December.

LocalDate start = LocalDate.of( 2018 , 1 , 23 ) ;  // 2018-01-23.

Collect a sequence of dates.

List<LocalDate> dates = new ArrayList<>( 7 ) ;
for( int i = 1 ; i <= 7 ; i ++ ) {
    LocalDate ld = start.minusDays( i ) ;  // Determine previous date.
    dates.add( ld ) ;  // Add that date object to the list. 
}

For earlier Android, use the ThreeTen-Backport and ThreeTenABP projects.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...