简体   繁体   中英

Setting up alarm for current or future date

I am currently grabbing a date format from the database and it has the format of HH:mm eg 10:00.

Then I change the time format so that it can be in milis to set up a repeating alarm:

SimpleDateFormat format = new SimpleDateFormat("HH:mm");
String time = collectionString;

long timeOfFirstCollectionInMillis = format.parse(time).getTime();
System.out.println(collectionInMillis);

//Set Alarm to Repeat
manager.setRepeating(AlarmManager.RTC_WAKEUP,collectionInMillis, interval, pendingIntent);

The problem is it thinks that the date has already passed because there's no date attached to the time (I think). How can I set it so that if the time has passed, like it's 11:00am but the time was supposed to be for 10:00am, to set it for a future date and if the the time is 9:00am but the time is for 10:00am for the current date?

I would use the Calendar class for this. So basically:
- set the time to a calendar and also set the date to today
- compare that with a current timestamp
- if it is before the current time then set it to a future date (next hour, next day, ...)
- if it is after the current time you can use it as is

So roughly:

Calendar now = Calendar.getInstance();
now.setTime(new Date());

Calendar cal = Calendar.getInstance();
cal.setTime(timeOfFirstCollectionInMillis);
cal.set(Calendar.YEAR, now.get(Calendar.YEAR));

Do the same for month and day...and then:

if (cal.before(now)) {
   // increase
} else {
  timeOfFirstCollectionInMillis = cal.getTime();
}

I am guessing the output time here might of 24 hour format like for 11:00 pm it might be 23:00.

Hope this helps.

Joda-Time

Here is the same kind of code as in the other answer by Carsten but using the Joda-Time library. That answer basically works but fails to consider the crucial issue of time zone. And the java.util.Date/.Calendar classes are notoriously troublesome and should be avoided.

LocalTime time = LocalTime.parse( "10:00" );
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone );
DateTime target = now.withTime( now.getHourOfDay(), now.getMinuteOfHour(), now.getSecondOfMinute(), now.getMillisOfSecond() );
if ( target.isBefore( now ) ) {
    target = target.plusDays( 1 );
}
Duration duration = new Duration( now, target );
long millisUntilTarget = duration.getMillis();

In real work I would add a bit of padding. If millisUntilTarget were a very small number, that small duration might elapse before the rest of the app could sound the alarm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM