I am trying to create a function where I will send a specific date (e.g.
Calendar c = Calendar.getInstance();
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
Calendar and using better API's suited for date manipulation. The old classes (
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.
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
If you just want the next Sunday, regardless of week definitions, you can just use the
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
// creates 2017-09-16 LocalDate date = LocalDate.parse("2017-09-16");