【发布时间】:2013-11-12 07:42:30
【问题描述】:
我查看了相关问题的答案,但他们的解决方案没有奏效。我真的对从 NSDateComponents 和 NSDateFormatter 收到的输出感到困惑(以及 MTDates 以方便使用,但我尝试绕过它以获得不同的结果但无济于事)。
这是 UI 相关部分的链接(来自模拟器):http://grab.by/rFbQ
以及与问题相关的日志:
2013-10-31 23:58:03.407 Application[22530:70b] Date 2013-11-01 04:58:03 +0000
2013-10-31 23:58:03.408 Application[22530:70b] Formatted Date Oct 31, 2013, 11:58:03 PM
2013-10-31 23:58:03.408 Application[22530:70b] Hours 17
2013-10-31 23:58:03.408 Application[22530:70b] Minutes 9
用于获取数字的代码:
[NSDate mt_setTimeZone:[NSTimeZone localTimeZone]];
NSDate *current = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterMediumStyle];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents *comp = [cal components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:current];
NSUInteger hours = comp.hour;
NSUInteger minutes = ceil([current mt_minuteOfHour] / 6);
NSLog(@"Date %@", current);
NSLog(@"Formatted Date %@", [formatter stringFromDate:current]);
NSLog(@"Hours %lx", hours);
NSLog(@"Minutes %lx", minutes);
self.dateLabel.text = [formatter stringFromDate:current];
self.timeLabel.text = [NSString stringWithFormat:@"%lx.%lx", hours, minutes];
我不知道您是否可以从上面的输出中看出,但格式化的日期(对于正确的时区)将小时显示为“11”(“11:58:03”),这让我感到困惑,即使设置NSCalendar 和 NSDateFormatter 的时区与 NSTimeZone (localTimeZone) 我得到“17”作为当前时间。
我还应该提到我正在使用MTDates 来增加日期操作,但在我包含这个库之前遇到了这个问题(希望它的包含可能会以某种方式使这些结果更加合理)。话虽如此,我也尝试将我获取自己的组件的部分替换为:
NSUInteger hours = [current mt_hourOfDay];
不幸的是,这也返回“17”。我希望它返回“23”,但会对“11”感到满意,然后可以将其转换为 24 比例。
【问题讨论】:
-
%x格式说明符用于十六进制。使用%d表示十进制(以 10 为基数)。十进制的 23 是十六进制的 17。 -
@maddy 哇...我现在觉得自己像个白痴还是什么。我对格式化组件的不熟悉和文档中缺乏规范(来自文档的
NSUInteger %lu or %lx)导致我盲目地四处走动。我从来没有想过这个想法。如果您不介意在答案中写出来(我意识到这并不多),我会给您接受。这是我的问题的解决方案。 -
有时是小事。 :) 看我的回答。
标签: ios objective-c ios7 nsdate nsdatecomponents