views:

375

answers:

3

I'd like to make a countdown to the next full hour. It's pretty easy to countdown to a specific time, like:

NSDate *midnight = [NSDate dateWithNaturalLanguageString:@"midnight tomorrow"]; 

how do I define an NSDate for "the beginning of every hour"?

Thanks!

EDIT: This is what I have currently. Having trouble integrating the solutions in to my code. Any help would be greatly appreciated. :)

-(void)updateLabel {
NSDate *now = [NSDate date];

NSDate *midnight = [NSDate dateWithNaturalLanguageString:@"midnight tomorrow"]; 

//num of seconds between mid and now
NSTimeInterval timeInt = [midnight timeIntervalSinceDate:now];
int hour = (int) timeInt/3600;
int min = ((int) timeInt % 3600) / 60;
int sec = (int) timeInt % 60;
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, min,sec];
}  
A: 

Hi,

First of all I want to make clear that the method you are using is non-documented so it will possible cause rejection of ur app.

Now you can define the NSDate (if I understand ur question) like this:

NSDate *nextHr = [NSDate dateWithTimeIntervalSinceNow:3600];

or you can also do this

NSDate *nextHr = [[NSDate alloc] initWithTimeInterval:3600 sinceDate:RefDate];

Hope this helps.

Thanks,

Madhup

Madhup
That will give you a date exactly an hour after current one - not the beginning of next hour
Vladimir
+4  A: 

As +dateWithNaturalLanguageString is available on MacOS SDK only and your're targeting iPhone you'll need to make a method of your own. I think NSCalendar class can help you:

- (NSDate*) nextHourDate:(NSDate*)inDate{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components: NSEraCalendarUnit|NSYearCalendarUnit| NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit fromDate: inDate];
    [comps setHour: [comps hour]+1]; // Here you may also need to check if it's the last hour of the day
    return [calendar dateFromComponents:comps];
}

I have not checked this code but it (at least this approach) must work.

Vladimir
The code given will currently work (even if the next hour is midnight), but I think you should technically use NSCalendar's `dateByAddingComponents:toDate:` rather than manually adding the components. NSCalendar is the right answer, though.
Chuck
Yes dateByAddingComponents:toDate looks more appropriate, but you still need to reset minute and second components to 0 somehow?
Vladimir
thanks guys but I can't get this to work.. :)
dot
What doesn't work exactly? I've just run this code - it works ok for me (still don't know if it will work in case next hour is midnight)
Vladimir
hi vladimir.. I've added some details to my original question. Thansk!
dot
replace dateWithNaturalLanguageString call with call to nextHourDate ?
Vladimir
+3  A: 

You might want to check this out. Erica Sadun posted some extensions to NSDate.

http://github.com/erica/NSDate-Extensions

xyzzycoder