7

I'm using Java's calendar to set an alarm at a specific date and time. I know how to make this work when the user selects a specific date and time. For example, if the user wants to set an alarm on July 17th, 2013 at 10:45AM, I'm using the following code:

//Get the calendar instance.
Calendar calendar = Calendar.getInstance();       

//Set the time for the notification to occur.
calendar.set(Calendar.YEAR, 2013);
calendar.set(Calendar.MONTH, 6);
calendar.set(Calendar.DAY_OF_MONTH, 17);                 
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 45);
calendar.set(Calendar.SECOND, 0);

All of the above code works really well when I want to set an alarm at a specific date and time. My question is, how can I set a calendar instance where the user user wants an alarm to go off 20 minutes from the current date and time? So if the current time is 6:50PM, I need the alarm to go off at 7:10PM. How can I set this programmatically?

I tried to get the current date and time via the Java.util.calendar's built-in methods and tried adding 20 minutes to the Calendar.MINUTE variable. However, I don't think this will do the trick if the current time is less than 20mins away from midnight (the date will change), or 20mins away from another hour (the hour will change). How can I get around this problem? Thanks for all your help!

bool.dev
  • 17,508
  • 5
  • 69
  • 93
NewGradDev
  • 1,004
  • 6
  • 16
  • 35

3 Answers3

5

You want to look at calendar.add , it will increment the next field if you get overflow.

http://developer.android.com/reference/java/util/Calendar.html

digidigo
  • 2,534
  • 20
  • 26
  • Thanks! I'm new to Java so I didn't know about that method. It's exactly what I was looking for though. Thanks again! :) – NewGradDev Sep 29 '12 at 02:18
4

You can also try this

 Calendar c = Calendar.getInstance();
 c.setTime(new Date()); // 
 c.add(Calendar.YEAR, 5); // Add 5 years to current year
 c.add(Calendar.DATE, 5); // Add 5 days to current date
 c.add(Calendar.MONTH, 5); // Add 5 months to current month
 System.out.println(c.getTime());
Zuko
  • 2,764
  • 30
  • 30
1

You can try the calendar.set methods specified in this links. How to set the calendar in android for particular hour This worked for me , when I wanted to run the service on the specified time.

Community
  • 1
  • 1
Chetan
  • 1,141
  • 2
  • 15
  • 36