How to countdown from NSDate and display it in hours and minutes

I am trying to make a countdown from NSDate and display it in hours and minutes. Something like this: 1h: 18min

At the moment, my date is being updated to UILabel and is being counted, but displayed like this:

timer countdown label

Here is the code I'm using. StartTimer method and updateLabel method

- (void)startTimer { // Set the date you want to count from // convert date string to date then set to a label NSDateFormatter *dateStringParser = [[NSDateFormatter alloc] init]; [dateStringParser setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.000Z"]; NSDate *date = [dateStringParser dateFromString:deadlineDate]; NSDateFormatter *labelFormatter = [[NSDateFormatter alloc] init]; [labelFormatter setDateFormat:@"HH-dd-MM-yyyy"]; NSDate *countdownDate = [[NSDate alloc] init]; countdownDate = date; // Create a timer that fires every second repeatedly and save it in an ivar NSTimer *timer = [[NSTimer alloc] init]; timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES]; } - (void)updateLabel { // convert date string to date then set to a label NSDateFormatter *dateStringParser = [[NSDateFormatter alloc] init]; [dateStringParser setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.000Z"]; NSDate *date = [dateStringParser dateFromString:deadlineDate]; NSDateFormatter *labelFormatter = [[NSDateFormatter alloc] init]; [labelFormatter setDateFormat:@"HH-dd-MM"]; NSTimeInterval timeInterval = [date timeIntervalSinceNow]; ///< Assuming this is in the future for now. self.deadlineLbl.text = [NSString stringWithFormat:@"%f", timeInterval]; } 

thanks for any help

+4
source share
2 answers
 - (NSString *)stringFromTimeInterval:(NSTimeInterval)interval { NSInteger ti = (NSInteger)interval; NSInteger seconds = ti % 60; NSInteger minutes = (ti / 60) % 60; NSInteger hours = (ti / 3600); return [NSString stringWithFormat:@"%02i:%02i:%02i", hours, minutes, seconds]; } 
+8
source

Since you use NSTimeInterval, you get the time interval, that is, the difference, in seconds, in order to display it in hours and minutes, you need to apply the mathematical logic and convert it! You need a few loops to do this.

try it

Hello

+2
source

Source: https://habr.com/ru/post/1445752/


All Articles