java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time
, the modern Date-Time API:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
public class Main {
public static void main(String[] args) {
// Replace JVM's ZoneId, ZoneId.systemDefault() with the applicable one e.g.
// ZoneId.of("America/Los_Angeles")
LocalDate today = LocalDate.now(ZoneId.systemDefault());
// Next Sunday
LocalDate nextSun = today.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
System.out.println(nextSun);
// Same (if it's Sunday today) of next Sunday
LocalDate sameOrNextSun = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
System.out.println(sameOrNextSun);
// Previous Sunday
LocalDate previousSun = today.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY));
System.out.println(previousSun);
// Same (if it's Sunday today) of previous Sunday
LocalDate sameOrPreviousSun = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
System.out.println(sameOrPreviousSun);
}
}
Output from a sample run:
2021-07-25
2021-07-18
2021-07-11
2021-07-18
ONLINE DEMO
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.