Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count Down Timer in iPhone

Tags:

iphone

I have two time.. one fetched directly as string(@"21:00") and other is the current time. I want to display a count down timer showing how much time left from now to reach 21:00.

For eg: the label i use should display "You have 3hrs and 30 minutes left.." if the current time is 17:30. thanks..

like image 646
Muhammed Sadiq.HS Avatar asked Feb 04 '26 06:02

Muhammed Sadiq.HS


2 Answers

OK have completely revised my answer, and have created a complete solution to the problem, with fully tested sample code available on github.

Enjoy :)

like image 106
Alex Coplan Avatar answered Feb 06 '26 19:02

Alex Coplan


Something like this should do it. This will give you the remaining time in seconds. Then you just need to to standard timer stuff as indicated in other answers.

//assumption: targetTime is after now
NSString *targetTime = @"21:00";

//split our time into components
NSArray *timeSplit = [targetTime componentsSeparatedByString:@":"];

NSUInteger hours =  [[timeSplit objectAtIndex:0] intValue];
NSUInteger minutes =  [[timeSplit objectAtIndex:1] intValue];

NSDate *now = [NSDate date];

//split now into year month day components
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [currentCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:now];

//set our time components from above
[dateComponents setHour:hours];
[dateComponents setMinute:minutes];

NSDate *targetDate = [currentCalendar dateFromComponents:dateComponents];

//ensure target is after now
if ([targetDate timeIntervalSinceDate:now] < 0)
{
    NSDateComponents *day = [[NSDateComponents alloc] init];
    [day setDay:1];

    targetDate = [currentCalendar dateByAddingComponents:day toDate:targetDate options:0]; 
}

NSTimeInterval timeRemaining = [targetDate timeIntervalSinceDate:now];
like image 26
Ian1971 Avatar answered Feb 06 '26 18:02

Ian1971



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!