关于 java:Android 日历:到达未来的一天

Android Calendar: Get to the future day

我想为用户选择的特定日期设置警报,当我设置为当前日期的前一天时,它将它设置为过去的日期,我希望它设置为未来。

这是我的日历设置代码:

1
2
3
4
5
6
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour.getHour());
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.Monday);

假设今天是星期四,当我将日期设置为星期一时,我希望它设置为 4 天后,但它设置为 3 天前,到星期一


您可以使用以下"技术":

  • 计算当前日期与您想在未来设置为日历的日期之间的天数差,例如

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    //future date
    Calendar thatDay = Calendar.getInstance();
    thatDay.set(Calendar.HOUR_OF_DAY, hour.getHour());
    thatDay.set(Calendar.MINUTE, 0);
    thatDay.set(Calendar.SECOND, 0);
    thatDay.set(Calendar.AM_PM, Calendar.AM);
    thatDay.set(Calendar.DAY_OF_WEEK, Calendar.Monday);

    //current date
    Calendar newDay = Calendar.getInstance();

    long diff = thatDay.getTimeInMillis() - newDay.getTimeInMillis(); //result in millis

    //result in days
    long days = diff / (24 * 60 * 60 * 1000);
  • 将步骤 1 中计算的天数添加到日历中,例如:

    1
    2
    3
    4
    5
    6
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, hour.getHour());
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.AM_PM, Calendar.AM);
    calendar.add(Calendar.DATE, daysCount); // Add daysCount days to current date

  • 你应该add而不是set。添加后,Calendar 实例将正确地前进或减去(您也可以添加负数)。

    通过设置属性之一,您可能必须处理所有回合和携带。