Search code examples
iosobjective-cnsdatensdateformatter

how to get hour with date format


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?


Solution

  • 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];