5

I have a time format like this

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"HH:mm:ss"];

from this, I need only HH value.

How to get that value?

Piotr Niewinski
  • 1,298
  • 2
  • 15
  • 27
sudheer
  • 418
  • 6
  • 20
  • http://stackoverflow.com/questions/10861433/in-objective-c-to-get-the-current-hour-and-minute-as-integers-we-need-to-use-n visit this – Aniket Kote Aug 21 '13 at 12:26
  • 8
    Wow... `HH:mm:ss` gives `12:45:32`, you need only `HH`... don't tell me you've searched for more than 4 seconds before posting this. – Cyrille Aug 21 '13 at 12:41

2 Answers2

10
NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc]init]autorelease];
timeFormatter.dateFormat = @"HH";


NSString *datestringofHour= [timeFormatter stringFromDate: localDate];

Now in datestringofHour variable you will have hour value as a string.

Another one as follows which can give you hour,minute,seconds in integer value

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]]; 

NSInteger hour= [components hour];   
NSInteger minute = [components minute];
NSInteger second = [components second]; 
BhavikKama
  • 8,566
  • 12
  • 94
  • 164
3

Just switch:

[df setDateFormat:@"HH:mm:ss"];

to:

[df setDateFormat:@"HH"];
Abdullah Shafique
  • 6,878
  • 8
  • 35
  • 70