Android日历:开始未来的一天

时间:2015-07-02 11:34:10

标签: java android date calendar alarmmanager

我想设置一个警报到用户选择的具体日期,当我设置为当天前一天,它将它设置为过去的日期,我希望它设置为将来。

这是我的日历集代码:

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天前,直到星期一

2 个答案:

答案 0 :(得分:1)

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

  1. 计算日期'当前日期和您希望将来设置为日历的日期之间的差异,例如

    //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);
    
  2. 将您在步骤1中计算的天数添加到日历中,例如:

    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
    

答案 1 :(得分:0)

您应该add而不是set。添加Calendar实例后,将正确推进或减去(也可以添加否定)。

通过设置其中一个属性,您可能需要处理所有轮次并执行。