javaandroid-calendarandroid-datedatejava-calendar

Get Start day and End day of a Week? [Java]


I am developing an app that constantly monitors the user's physical activity and inactivity levels. I am trying to figure out out to get the starting and ending day of a week when a date is provided. For example, 3 Mar is the date that I am providing and I want to get the starting and ending day of this week -> 27 Feb - 5 Mar. Is it possible to do that?

I am trying to achieve the following design enter image description here

The following code that I currently have just concatenates the last and first date of the list of activities (one for every day is created).

private String formatDate(List<Activity> activities) {
    Calendar calendar = Calendar.getInstance(Locale.UK);
    Date date = activities.get(activities.size() - 1).getDate();
    calendar.setTime(date);
    String output = "" + calendar.get(Calendar.DAY_OF_MONTH) + " "
            + calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.UK);

    calendar.setTime(activities.get(0).getDate());

    output += " - " + calendar.get(Calendar.DAY_OF_MONTH) + " "
            + calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.UK);
    return output;
}

Note: I have to mention that the List as a parameter are all of the activities grouped per week already

However, with this approach it becomes problematic when the person is not using the app (i.e. not logged in -> the app stops monitoring) and the text label could look something like that enter image description here (e.g. only one activity for this week)

Any advice please?


Solution

  • It is as simple as doing:

    calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
    

    What is considered the first day of the week depends on the Locale used.

    To get the last day of the week then do:

    calendar.add(Calendar.DAY_OF_YEAR, 6);