Reputation: 171
How do I get the current hour in Cocoa using Objective-C?
Upvotes: 4
Views: 11455
Reputation: 15748
Swift version
func currentHour() -> Int {
let now = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.Hour, fromDate: now)
return components.hour
}
Upvotes: 0
Reputation: 21
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.
Upvotes: 2
Reputation: 78353
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];
}
Upvotes: 39
Reputation: 75058
[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?
Upvotes: 1
Reputation: 14458
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];
Upvotes: 6