在 1 周前添加后,将week_of_month设置回当前



假设我有以下代码:

String day = "12";
Calendar calendar = Calendar.getInstance();
int week_of_month = calendar.get(Calendar.WEEK_OF_MONTH);
int day_of_week = calendar.get(Calendar.DAY_OF_WEEK); //For example, today is Monday
calendar.set(Calendar.HOUR_OF_DAY, 07);
calendar.set(Calendar.MINUTE, 05);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
if (day.contains("1")){ //here I set calendar day to Monday
        calendar.set(Calendar.WEEK_OF_MONTH, week_of_month);
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        if (day_of_week == Calendar.MONDAY) {
            if (System.currentTimeMillis() > calendar.getTimeInMillis()) {
                calendar.add(Calendar.WEEK_OF_MONTH, 1);
                //I add one week in case today is Monday but 07:05 was in the past
//THE PROBLEM IS CAUSED HERE..
            }
        }
  }
if (day.contains("2")){ //here I set calendar day to Tuesday
        **calendar.set(Calendar.WEEK_OF_MONTH, week_of_month); //This seems not working for some reason**
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
            if (day_of_week == Calendar.TUESDAY) {
            if (System.currentTimeMillis() > calendar.getTimeInMillis()) {
                calendar.add(Calendar.WEEK_OF_MONTH, 1);
                //In the example, today is Monday so this code is not running
            }
        }
 }

问题是在第一个 if 语句中,日历日期设置正确(即使 System.currentTimeMillis((> calendar.getTimeInMillis(((。但是,在第二个 if 语句中,如果我在第一个 if 语句中添加了一周前的日历日期,则日历日期设置为下周的星期二,而不是本周的星期二。

您可以将时间(以毫秒为单位(设置为系统的当前时间。

calendar.setTimeInMillis(System.currentTimeMillis());

最新更新