java.time and ThreeTenABP
If you want to use java.time, the modern Java date and time API, it can be done with this simple method:
private static WeekFields wf = WeekFields.of(Locale.forLanguageTag("ne-NP"));
public static void getWeeklyDateList(int year, Month month, int week) {
LocalDate someDateInTheWeek = LocalDate.of(year, month, 10).with(wf.weekOfMonth(), week);
LocalDate start = someDateInTheWeek.with(wf.dayOfWeek(), 1);
LocalDate end = someDateInTheWeek.with(wf.dayOfWeek(), 7);
System.out.println("date_start: " + start);
System.out.println("date_end: " + end);
}
Trying it out with your example arguments:
getWeeklyDateList(2020, Month.JUNE, 3);
Output is:
date_start: 2020-06-14
date_end: 2020-06-20
How it works:
First, weeks are defined differently in different cultures. In Nepal (since you give Kathmandu, Nepal as your location) weeks start on Sunday and are numbered in a way where the 1st of the month is in week 1 of the month. To handle this week scheme I am initializing a WeekFields
object for Nepalese culture.
LocalDate
is the java.time class for a date without time of day. I don’t think it matters which day of the month I pick as a starting point; I took the 10th. From that date I get a date in the correct week, using the WeekFields
object and the supplied week number. From there in turn I get the first and the last day of the week, again according to the Nepalese definition of weeks: from Sunday June 14 through Saturday June 20 2020.
What went wrong in your code I cannot tell. In any case the Calendar
class you used is poorly designed and long outdated. It also default uses the default locale of the JVM for its week definition, which may have given you a different week scheme from what you wanted. A final point that may have confused you: Calendar
unnaturally numbers months from 0 for January through 11 for December. So when you specified 5, you got June (not May). You printed out the month numbers of your result dates, which probably again printed 5 (not 6) for June.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links