0

i want to set an alarm to the specific date choosen by user, when i set to the day before current day, it sets it to past date, i want it to set to future.

Here is my Calendar set code:

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);

let's say today is thursday, when i set date to monday, i want it to set to 4 days later, but it sets to 3 days before, to past monday

eduyayo
  • 2,020
  • 2
  • 15
  • 35
kakajan
  • 2,614
  • 2
  • 22
  • 39
  • possible duplicate of [How to add days to a date in Java](http://stackoverflow.com/questions/2507377/how-to-add-days-to-a-date-in-java) – Basil Bourque Jul 02 '15 at 21:14

2 Answers2

1

You could use the following "technology":

  1. calculate the days' difference between the current day and the day that you want to set to the calender in the future like this for example

    //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. add to the calendar so many days as you calculated in step 1 like this for example:

    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
    
Gabriella Angelova
  • 2,985
  • 1
  • 17
  • 30
0

You should add and not set. Once you add the Calendar instance will advance or substract (you can add negative, also) correctly.

By setting one of the properties you may have to handle all rounds and carries.

eduyayo
  • 2,020
  • 2
  • 15
  • 35