Retrieving hours in 24 hour format in iphone

2019-09-21 15:08发布

问题:

I am using this format to get hours

   NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"hh";
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];

    NSString *date = [dateFormatter stringFromDate:now];

    NSInteger myHour = [date intValue];

The problem is it returns e.g 4Pm i Want it to return 16 Instead of 4. How can I do that? I tried replacing hh by single h by of no avail.

回答1:

Here Your input:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh"];
NSDate *Yourcurrenttime = [dateFormatter dateFromString:Yourstring];

And date converted to the String ..

[dateFormatter setDateFormat:@"HH"];
NSString *date = [dateFormatter stringFromDate:now];

NSInteger myHour = [date intValue];


回答2:

Here is answer :-

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"HH";
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];

    NSString *date = [dateFormatter stringFromDate:[NSDate date]];

    NSInteger myHour = [date intValue];
    NSLog(@"%d",myHour);

Hope it helps you!



回答3:

Its for 12 hour time format :-

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"hh a"];
NSString *theTime = [timeFormat stringFromDate:[NSDate date]];    
NSLog(@"time, %@",theTime);  

Its for 24 hour time format:-

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH"];
NSString *theTime = [timeFormat stringFromDate:[NSDate date]];    
NSLog(@"time, %@",theTime);