每天24小时的NSDate时间?

我有这个date格式化程序:

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

如果我使用这个:

  NSDate *myDate = [timeFormatter dateFromString:@"13:00"]; 

它返回这个:

  "1:00" 

这是因为模拟器已经closures了24小时。 但对于我的应用程序,我真的需要"13:00"而不是"1:00"

编辑1

增加了新的代码:

 NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init]; [timeFormatter setDateFormat:@"HH:mm"]; NSDate *timeForFirstRow = [timeFormatter dateFromString:@"13:00"]; NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:timeForFirstRow]; NSInteger hour = [dateComponents hour]; //This will be 1 instead of 13 NSInteger minute = [dateComponents minute]; 

如果您想要将其强制为12小时制或24小时制模式,则无论用户的24/12小时模式设置如何,都应将date格式化程序的区域设置设置为en_US_POSIX(12小时)或en_GB为24小时模式。

那是,

 NSLocale* formatterLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"] autorelease]; [timeFormatter setLocale:formatterLocale]; 

更多的在这里:

http://developer.apple.com/iphone/library/qa/qa2010/qa1480.html

我最近有这个相同的问题,并遇到这个文件列出所有的date格式模式: http : //unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns

我可以通过使用k:mm作为date格式来获得24倍的工作时间:

 NSDateFormatter *format = [[NSDateFormatter alloc] init]; [format setDateFormat:@"k:mm"]; 

从Apple文档中 ,时间格式string遵循Unicode技术标准#35 。

如UTR#35所述,大写字母HH为您提供24小时的时间,小写字母则为您提供12小时的时间。

简而言之,如果您需要24小时制,请使用[timeFormatter setDateFormat:@"HH:mm"]; 如果你需要12小时的风格,使用[timeFormatter setDateFormat:@"hh:mm"];

你必须在这里两个步骤

 NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]; [formatter setLocale:locale]; [formatter setDateFormat:@"hh:mm a"]; 

这里格式化程序给出am / pm格式

如果有人帮我解决了一个问题,那就是我想用自己的设备来显示用户的时间:

 let timeFormatter = NSDateFormatter() timeFormatter.timeStyle = NSDateFormatterStyle.ShortStyle //get the time from the picker 

把时间发送到我们的API 24风格:

 timeFormatter.locale = NSLocale(localeIdentifier: "en_GB") //get the time again