【问题标题】:how to get hour with date format如何以日期格式获取小时
【发布时间】:2013-08-21 12:19:40
【问题描述】:

我有这样的时间格式

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

由此,我只需要HH值。

如何获得该值?

【问题讨论】:

标签: ios objective-c nsdate nsdateformatter


【解决方案1】:
NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc]init]autorelease];
timeFormatter.dateFormat = @"HH";


NSString *datestringofHour= [timeFormatter stringFromDate: localDate];

现在在datestringofHour 变量中,您将获得小时值作为字符串。

下面的另一个可以给你小时、分钟、秒的整数值

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

NSInteger hour= [components hour];   
NSInteger minute = [components minute];
NSInteger second = [components second]; 

【讨论】:

    【解决方案2】:

    只需切换:

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

    到:

    [df setDateFormat:@"HH"];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-28
      • 2020-06-02
      相关资源
      最近更新 更多