在iphone中以24小时格式检索小时数

时间:2012-10-06 11:52:29

标签: iphone objective-c cocoa-touch datetime

我使用这种格式来获得时间

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

    NSString *date = [dateFormatter stringFromDate:now];

    NSInteger myHour = [date intValue];

问题是它返回,例如4Pm我希望它返回16而不是4.我怎么能这样做?我尝试用单h代替hh无济于事。

3 个答案:

答案 0 :(得分:2)

这里您的输入:

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

并将日期转换为String ..

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

NSInteger myHour = [date intValue];

答案 1 :(得分:1)

以下是答案: -

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

希望它可以帮到你!

答案 2 :(得分:1)

12小时时间格式: -

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

24小时时间格式: -

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