每次24小时风格的NSDate小时数? [英] Hours in NSDate every time in 24-hour style?

查看:100
本文介绍了每次24小时风格的NSDate小时数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个日期格式化程序:

I have this date formatter:

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

如果我使用这个:

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

它返回:

 "1:00"

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

This is because the simulator has switched off 24-hour. But for my app I really need "13:00" instead of "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小时模式设置如何,您都应将日期格式化程序的区域设置设置为en_US_POSIX(12小时),或者设置为24小时模式的en_GB。

If you want to force it to 12-hour or 24-hour mode, regardless of the user's 24/12 hour mode setting, you should set the locale of the date formatter to en_US_POSIX (for 12-hour), or, say, en_GB for the 24-hour mode.

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

此处还有更多内容:

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

这篇关于每次24小时风格的NSDate小时数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆