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

前端 未结 3 812
暖寄归人
暖寄归人 2020-12-07 06:20
//explain
public class DateLoop {
    static String finalDate; 
    static String particularDate;

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


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 07:14

    As Uta Alexandru and Basil Bourque have said already, don’t use the long outmoted classes SimpleDateFormat and Calendar. java.time, the modern Java date and time API also known as JSR-310, is so much nicer to work with:

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d-M-uuuu");
        LocalDate date = LocalDate.parse("2-1-2018", dtf)
                .minusDays(7);
    
        for(int i = 0; i < 7; i++) {
            date = date.plusDays(1);
            String finalDate = date.format(dtf);
            System.out.println(finalDate);
        }
    

    This prints:

    27-12-2017
    28-12-2017
    29-12-2017
    30-12-2017
    31-12-2017
    1-1-2018
    2-1-2018
    

    Not only is the code slightly simpler and shorter, more importantly, it is clearer and more natural to read.

    Question: Can I use java.time on Android?

    You certainly can. It just requires at least Java 6.

    • In Java 8 and later the new API comes built-in.
    • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310).
    • On Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP.

    Links

    • Oracle tutorial: Date Time, explaining how to use java.time.
    • ThreeTen Backport project
    • ThreeTenABP, Android edition of ThreeTen Backport
    • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
    • Java Specification Request (JSR) 310, where the modern date and time API was first described.

提交回复
热议问题