ios - 如何使用日期格式获取小时

标签 ios objective-c nsdate nsdateformatter

我有这样的时间格式

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

由此,我只需要HH值。

如何获取该值?

最佳答案

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

关于ios - 如何使用日期格式获取小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18357246/

相关文章:

c++ - 使用g++编译Objective-C项目时出现运行时错误

swift - 如何从 NSDate(timeIntervalSince1970) 转换为 NSDate()?

swift 我当前的时间变量没有显示我的实际当前时间

ios - 属性要求在 objective-c 中命名字段错误

c++ - iOS NAT64 IPv6 环境问题

objective-c - 对实体数组进行迭代,并根据 "other key"匹配的值获取某个键的值

iphone - 当再次调用 loadView 时,iOS7 View 在状态/导航栏下移动

objective-c - 如何使用 Cocoa 查找任何给定日期的星期几

ios - uitableviewcell 内的 UIbutton 在滚动时没有响应

iphone - 带 URL 的 writeToFile - URL 在下一个 session 中不存在