Consider avoiding Calendar
and using better API's suited for date manipulation. The old classes (Date
, Calendar
and SimpleDateFormat
) have lots of problems and design issues, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java 6 or 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, you'll also need the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time
and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp
), but the classes and methods names are the same.
First you need to define what's the first day of the week, as it's not the same in all countries. You can use ISO's definition (Monday is the first day of the week), so your code will be like this:
LocalDate date = LocalDate.of(2017, 9, 16);
// use ISO definition (Monday is the first day of week)
WeekFields wf = WeekFields.ISO;
LocalDate sundayInSameWeek = date
// get the first day of this week
.with(wf.dayOfWeek(), 1)
// get next Sunday (or the same date, if it's already Sunday)
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
System.out.println(sundayInSameWeek); // 2017-09-17
The result is 2017-09-17
. But if I use a different definition of week (such as US's definition, where Sunday is the first day of the week):
LocalDate date = LocalDate.of(2017, 9, 16);
// use US's definition of week (Sunday is the first day of week)
WeekFields wf = WeekFields.of(Locale.ENGLISH);
LocalDate sundayInSameWeek = date ... // all the same code
The result will be 2017-09-10
, because in US, Sunday is the first day of week, so the "Sunday in the same week as 2017-09-17" is indeed 2017-09-10
.
If you just want the next Sunday, regardless of week definitions, you can just use the TemporalAdjusters
class:
LocalDate date = LocalDate.of(2017, 9, 16);
LocalDate nextSunday = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)); // 2017-09-17
If you have a String
with the date, you can parse it directly to a LocalDate
:
// creates 2017-09-16
LocalDate date = LocalDate.parse("2017-09-16");