我有这个日期格式化程序:
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:@"HH:mm"];
如果我使用它:
NSDate *myDate = [timeFormatter dateFromString:@"13:00"];
它返回:
"1:00"
这是因为模拟器已关闭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];
答案 0 :(得分:26)
如果要将其强制为12小时或24小时模式,无论用户的24/12小时模式设置如何,都应将日期格式化程序的区域设置设置为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
答案 1 :(得分:9)
我最近遇到了同样的问题,并且遇到了这个列出所有日期格式模式的文档:http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
我只能使用k:mm作为日期格式来完成24次工作:
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"k:mm"];
答案 2 :(得分:2)
从Apple Documentation开始,时间格式字符串会跟随Unicode Technical Standard #35。
如UTR#35所述,大写HH
为您提供24小时的时间表,而小写hh
为您提供12小时的时间表。
简而言之,如果您需要24小时制,请使用[timeFormatter setDateFormat:@"HH:mm"];
,如果您需要12小时制,请使用[timeFormatter setDateFormat:@"hh:mm"];
答案 3 :(得分:1)
你必须在这里完成两个步骤
NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
[formatter setLocale:locale];
[formatter setDateFormat:@"hh:mm a"];
这里格式化程序中的a给出am / pm格式
答案 4 :(得分:0)
如果它帮助了我刚刚遇到问题的任何人,我希望以他们在设备上设置的方式显示用户的时间:
let timeFormatter = NSDateFormatter()
timeFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
//get the time from the picker
以24种方式将时间发送到我们的API:
timeFormatter.locale = NSLocale(localeIdentifier: "en_GB")
//get the time again