Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to countdown from a NSDate and display it in hours and minutes. Like this: 1h:18min

At the moment my date is updating to a UILabel and counting down but displaying like this:

timer countdown label

Here's the code I'm using. A startTimer method and a 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

like image 697
hanumanDev Avatar asked Dec 21 '22 13:12

hanumanDev


1 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];
  }
like image 167
DD_ Avatar answered Feb 02 '23 00:02

DD_