Rac*_* Jr 4 date objective-c nsdate ios
我需要从iPhone项目中的UIDatePicker控件中检索午夜过后的小时数.datePickerMode设置为UIDatePickerModeTime,所以用户只能设置时间,没有日期.当用户完成并关闭UIDatePicker所在的视图时,可能会检索以下日期(作为示例):
NSDate *returnTime = timePicker.date;
NSLog(@"returnTime: %@", returnTime); // returns for example @"1970-01-01 10:13:00 PM +0000"
Run Code Online (Sandbox Code Playgroud)
如上所述,我正在寻找午夜过后的小时数.在上面的示例中,该值应该是22.我想通过创建一个NSDateFormatter对象来实现这一点,并让它以24小时时钟格式提取一天中的小时,因此使用setDateFormat:@"H"(大写H而不是'h'):
NSDateFormatter *formatHour = [[NSDateFormatter alloc] init];
[formatHour setDateFormat:@"H"];
NSInteger intHoursPastMidnight = [[formatHour stringFromDate:returnTime] integerValue];
Run Code Online (Sandbox Code Playgroud)
然而,这并不总是按预期工作.当用户在系统范围的首选项(即用户使用AM/PM)中禁用24小时时,intHoursPastMidnight将包含10而不是22.10确实是可见的价值UIDatePicker,但我原本期望将NSDateFormatter其转换22为@"H".
这有什么不对?我的转换假设不正确吗?这是UIDatePicker的错误吗?我如何解决问题,因此我基本上可以访问UIDatePicker中设置的午夜过后的小时数,与用户的12或24小时时钟偏好无关?无论如何这是要走的路吗?
明确的最终目标是检索午夜过后的分钟数(所以小时*60 +分钟,价值总是在0和1440之间).
Dav*_*ong 22
你可以用你的NSCalendar.
首先,得到你的约会对象:
NSDate *date = [timePicker date];
Run Code Online (Sandbox Code Playgroud)
接下来,将其转换为其日期组件:
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSIntegerMax fromDate:date];
Run Code Online (Sandbox Code Playgroud)
现在我们将重置日期组件的小时和分钟,以便它现在指向午夜:
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
Run Code Online (Sandbox Code Playgroud)
接下来,我们将其转回日期:
NSDate *midnight = [[NSCalendar currentCalendar] dateFromComponents:components];
Run Code Online (Sandbox Code Playgroud)
最后,我们会询问午夜和日期之间的时间:
NSDateComponents *diff = [[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:midnight toDate:date options:0];
NSInteger numberOfHoursPastMidnight = [diff hour];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3845 次 |
| 最近记录: |