Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDate for "beginning of next hour"

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];
}  
like image 995
dot Avatar asked Feb 22 '10 07:02

dot


2 Answers

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.

like image 127
Vladimir Avatar answered Nov 02 '22 22:11

Vladimir


Using DateComponents and Date, you get it by adding a negative amount of minutes and one hour to the given date.

Swift3 (as an extension):

extension Date {
    public var nextHour: Date {
        let calendar = Calendar.current
        let minutes = calendar.component(.minute, from: self)
        let components = DateComponents(hour: 1, minute: -minutes)
        return calendar.date(byAdding: components, to: self) ?? self
    }
}

Use it with let nextHourDate = myDate.nextHour

See Apple Date and Time Programming Guide for reference.

===========================================================================

ObjectiveC (as a static method):

+ (NSDate *)nextHourDate:(NSDate *)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSMinuteCalendarUnit|NSHourCalendarUnit fromDate:date];
    components.minute = -components.minute;
    components.hour = 1;
    return [calendar dateByAddingComponents:components toDate:date options:0];
}

And call it with :

[YourClass nextHourDate:yourDate];
like image 40
dulgan Avatar answered Nov 02 '22 22:11

dulgan