1

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" .

Lina
  • 31
  • 5
  • 4
    What have you tried so far? Are you stuck somewhere? – QBrute Mar 15 '21 at 11:22
  • The adjustment will be of the form (date_number + offset) % 7. Offset will be a compile time constant, you can figure it out by trial and error. Java is infamous in setting JANARY to be month number zero. It probably does something equally hideous with the days of the week. – Bathsheba Mar 15 '21 at 11:24
  • 1
    Does this answer your question? [How to get the last Sunday before current date?](https://stackoverflow.com/questions/12783102/how-to-get-the-last-sunday-before-current-date) Look at the answer from Grzegorz Gajos which is the first answer after the accepted answer. – Abra Mar 15 '21 at 11:29
  • 1
    [Just undoing the seemingly automatic downvote that's programmed into the Java tag] – Bathsheba Mar 15 '21 at 11:31
  • 1
    Welcome to Stack Overflow. Please learn that you are supposed to search before asking a question here and when you post a question, tell us what your search brought up and specify how it fell short of solving your problem. It’s for your own sake since (1) you often find a better answer faster that way (2) it allows us to give preciser and more focused answers. It also tends to prevent or at least reduce the number of downvotes. – Ole V.V. Mar 15 '21 at 12:22

1 Answers1

7

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110