4

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

Jason Coco
  • 77,985
  • 20
  • 184
  • 180
ksnr
  • 171
  • 2
  • 4
  • 10

5 Answers5

39

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
  • 77,985
  • 20
  • 184
  • 180
6

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
  • 14,322
  • 9
  • 47
  • 46
2

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.

luvieere
  • 37,065
  • 18
  • 127
  • 179
Stephen
  • 21
  • 1
1
[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
  • 74,769
  • 26
  • 128
  • 150
0

Swift version

func currentHour() -> Int {
    let now = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components(.Hour, fromDate: now)

    return components.hour
}
Vojtech Vrbka
  • 5,342
  • 6
  • 44
  • 63
Marián Černý
  • 15,096
  • 4
  • 70
  • 83