How do I get the current hour in Cocoa using Objective-C?
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];
[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?
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];
}
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.