How do you convert the .minute() and the .hour() to Objective-C ?
func nearestHour () -> Int {
let halfHour = NSDate.minuteInSeconds() * 30
var interval = self.timeIntervalSinceReferenceDate
if self.seconds() < 30 {
interval -= halfHour
} else {
interval += halfHour
}
let date = NSDate(timeIntervalSinceReferenceDate: interval)
return date.hour()
}
I tried this:
- (int) nearestHour {
NSInteger halfHour = [NSDate minuteInSeconds].intValue * 30;
NSTimeInterval interval = [self timeIntervalSinceReferenceDate];
if ([self seconds] < 30) {
interval -= halfHour;
}
else {
interval += halfHour;
}
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate: interval];
return [date hour];
}
I get the following errors on these lines:
if ([self seconds] < 30) {
no visible @interface for NSDate declares the selector seconds.
return [date hour];
no visible @interface for NSDate declares the selector hour.
As mentioned NSDate doesn't have the interface you need. You need to break it out to a calendar interface. Then you can set the hour/minute/seconds and such individually or get them or whatever you need to do.
NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:self];
if ([components seconds] < 30) {
For your example :
- (int) nearestHour {
NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:self];
NSInteger halfHour = [NSDate minuteInSeconds].intValue * 30;
NSTimeInterval interval = [self timeIntervalSinceReferenceDate];
if ([components minutes] < 30) {
interval -= halfHour;
}
else {
interval += halfHour;
}
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate: interval];
return [date hour];
}
Lots of examples on SO and google : How do I get the current hour using Cocoa?