Reputation: 4061
I need the iPhone to recognize the current time (which I can do fine with NSDate) and have it countdown to the next time interval, say every half hour on the half hour. Example: if the current time is 2:12:30 and the interval is every half hour, I want a countdown to start at 17:30 (17 min 30 seconds left) and go to 0.
Code welcome, but also general program design thoughts welcome too. Here's the code I have for starting a countdown and getting the current time:
-(void)updateCounter:(NSTimer *)theTimer {
if(secondsLeft > 0 ){
secondsLeft -- ;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft % 3600) % 60;
waitingTimeLabel.text = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
}
else{
secondsLeft = 10;
}
}
-(void)countdownTimer{
//secondsLeft = minutes = seconds = 0;
if([timer isValid])
{
[timer release];
}
// NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
//[pool release];
}
-(NSDate *)getCurrentTime
{
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"mm:ss";
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSLog(@"The Current Time is %@",[dateFormatter stringFromDate:now]);
//[dateFormatter release];
NSString *currentTime = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:now]];
currentTimeLabel.text = currentTime;
return now;
}
Upvotes: 0
Views: 1544
Reputation: 80265
NSDate *now = [NSDate date];
int interval = 30*60; // half hour
long int nowSeconds = (long int) [now timeIntervalSince1970];
int secondsLeft = interval - (nowSeconds % interval);
NSDate *nextIntervalDate = [NSDate
dateWithTimeIntervalSince1970:nowSeconds+secondsLeft];
NSLog(@"Now is %@", now);
NSLog(@"The next interval point in time is %@", nextIntervalDate);
NSLog(@"That's another %d seconds (or %02d:%02d)",
secondsLeft, secondsLeft/60, secondsLeft%60);
Upvotes: 3