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];
}
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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With