javadatedatetime-formatjava-calendar

How to get previous/last Saturday for a given date in Java?


For example:- String fromDate="09/18/2020"; I want my actual fromDate to be last Saturday that is "09/12/2020" .

Another example:- String fromDate="09/01/2020"; I want my actual fromDate to be last Saturday that is "08/29/2020" .


Solution

  • TemporalAdjusters.previous

    import java.time.DayOfWeek;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.time.temporal.TemporalAdjusters;
    import java.util.Locale;
    
    public class Main {
        public static void main(String[] args) {
            String fromDate = "09/18/2020";
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/u", Locale.ENGLISH);
    
            LocalDate date = LocalDate.parse(fromDate, dtf);
    
            LocalDate result = date.with(TemporalAdjusters.previous(DayOfWeek.SATURDAY));
    
            // Default LocalDate#toString implementation
            System.out.println(result);
    
            // Formatted
            System.out.println(result.format(dtf));
        }
    }
    

    Output:

    2020-09-12
    9/12/2020
    

    Learn more about the modern date-time API from Trail: Date Time.


    For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.