views:

709

answers:

4

How do I get the current hour in Cocoa using Objective-C?

+1  A: 

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];
andi
+1  A: 
[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?

Kendall Helmstetter Gelner
+8  A: 

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];
}
Jason Coco
Upvote for link to documentation.
Matthew Schinckel
+1 for stating the calls can be chained
Abizern
A: 

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.

Stephen