How do I get the current hour in Cocoa using Objective-C?
5 Answers
To start off, you should read Dates and Times Programming Topics for Cocoa. That will give you a good understanding of using the various date/time/calendar objects that are provided in Cocoa for high-level conversions of dates.
This code snip, however, will answer your specific problem:
- (NSInteger)currentHour
{
// In practice, these calls can be combined
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now];
return [components hour];
}

- 77,985
- 20
- 184
- 180
-
Better yet watch the WWDC videos and see this week's NSHipster – uchuugaka Mar 21 '15 at 05:40
One way is to use NSCalendar and NSDateComponents
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now];
NSInteger hour = [components hour];

- 14,322
- 9
- 47
- 46
I am new to Cocoa as well, and I am quite glad I found this. I also want to include that you can easily make this a function returning the current hour, minute and second in one NSDateComponents object. like this:
// Function Declaration (*.h file)
-(NSDateComponents *)getCurrentDateTime:(NSDate *)date;
// Implementation
-(NSDateComponents *)getCurrentDateTime:(NSDate *)date
{
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:NSHourCalendarUnit + NSMinuteCalendarUnit + NSSecondCalendarUnit fromDate:now];
return comps;
}
// call and usage
NSDateComponents *today = [self getCurrentDateTime:[NSDate date]];
hour = [today hour];
minute = [today minute];
second = [today second];
As you can see the components parameter in the NSCalendar object is a bit wise enum and you can combine the enum values using a '+'
Just thought I would contribute since I was able to use the examples to create mine.
[NSDate date]
That's the current time, parse out the hour as needed. You didn't provide a lot of detail around exactly what hour you meant - formatted to a the current timezone for example? Or a different one?

- 74,769
- 26
- 128
- 150
Swift version
func currentHour() -> Int {
let now = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.Hour, fromDate: now)
return components.hour
}

- 5,342
- 6
- 44
- 63

- 15,096
- 4
- 70
- 83