Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Java.util.calendar to a specific time period in the future

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!

like image 327
NewGradDev Avatar asked Sep 29 '12 01:09

NewGradDev


People also ask

How do I set the time on my Java calendar?

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.

What is calendar getInstance () in Java?

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.

Can you format calendar class Java?

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.

How do you set a calendar value?

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.


1 Answers

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

like image 112
digidigo Avatar answered Sep 22 '22 10:09

digidigo