Retrieving hours in 24 hour format in iphone

浪子不回头ぞ 提交于 2019-12-25 18:25:07

问题


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);


来源:https://stackoverflow.com/questions/12759539/retrieving-hours-in-24-hour-format-in-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!