hanumanDev
hanumanDev

Reputation: 6614

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

Upvotes: 4

Views: 1972

Answers (2)

DD_
DD_

Reputation: 7398

- (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];
  }

Upvotes: 8

DD_
DD_

Reputation: 7398

Since you use NSTimeInterval ,you are getting the time interval ,ie the difference, in seconds, to display it in hours and minutes you need to apply mathematics logic and convert it! You many need a few loops to do it.

try this

Regards

Upvotes: 1

Related Questions