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!
Calendar setTime() Method in Java with ExamplesThe setTime(Date dt) method in Calendar class is used to set Calendars time represented by this Calendar's time value, with the given or passed date as a parameter. Parameters: The method takes one parameter dt of Date type and refers to the given date that is to be set.
The getInstance() method in Calendar class is used to get a calendar using the current time zone and locale of the system. Syntax: public static Calendar getInstance() Parameters: The method does not take any parameters. Return Value: The method returns the calendar.
The DateFormat class in Java is used for formatting dates. A specified date can be formatted into the Data/Time string. For example, a date can be formatted into: mm/dd/yyyy.
set(int, int, int, int, int, int) method sets the values for the calendar fields YEAR, MONTH,DAY_OF_MONTH,HOUR_OF_DAY,MINUTE and SECOND.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With