简体   繁体   中英

how to get the start and end date of specific week of a month

I'm trying to get the start and end date of specific week of a month. However the date is incorrect. Can anyone identify what's the issue?

public class DateUtils
{
   getWeeklyDateList(2020,5, 3);

  public static void getWeeklyDateList(int year, int month, int week)
  {
      Calendar calendar = Calendar.getInstance(Locale.getDefault());
      // setting year, month, week
      calendar.set(Calendar.YEAR, year);
      calendar.set(Calendar.MONTH, month);
      calendar.set(Calendar.WEEK_OF_MONTH,week);

    // setting day of week to first --> Sunday
    calendar.set(Calendar.DAY_OF_WEEK, 1);

    int year1 = calendar.get(Calendar.YEAR);
    int month1 = calendar.get(Calendar.MONTH);
    int day1 = calendar.get(Calendar.DAY_OF_MONTH);

    // setting day of week to last --> Saturday
    calendar.set(Calendar.DAY_OF_WEEK, 7);

    int year7 = calendar.get(Calendar.YEAR);
    int month7 = calendar.get(Calendar.MONTH);
    int day7 = calendar.get(Calendar.DAY_OF_MONTH);

    Log.e("date_start", String.valueOf(year1) + "-" + String.valueOf(month1) + "-" + String.valueOf(day1));
    Log.e("date_end", String.valueOf(year7) + "-" + String.valueOf(month7) + "-" + String.valueOf(day7));
} }

The main issue is that Calendar.MONTH start from 0 instead 1 So Calendar.JANUARY = 0 and Calendar.MAY = 4 When you set calendar.set(Calendar.MONTH, 5) is equivalent to calendar.set(Calendar.MONTH, Calendar.JUNE) and not calendar.set(Calendar.MONTH, Calendar.MAY). below a working version

public static void getWeeklyDateList(int year, int month, int week) {
    Calendar calendar = Calendar.getInstance(Locale.getDefault());
    // setting year, month, week
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, month - 1);
    calendar.set(Calendar.WEEK_OF_MONTH, week);

    // setting day of week to first --> Sunday
    calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);

    Date startDay = calendar.getTime();

    // setting day of week to last --> Saturday
    calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);

    Date endDay = calendar.getTime();

    SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");

    Log.e("date_start : ", dateFormat.format(startDay));
    Log.e("date_end : ", dateFormat.format(endDay));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM