ios - NSDateComponents(通过 MTDates)返回一个奇怪的小时数(mt_hourOfDay)

标签 ios objective-c ios7 nsdate nsdatecomponents

我看了相关的问题和答案,他们的解决方案没有奏效。我对从 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”),这让我很困惑,即使设置NSCalendarNSDateFormatter 的时区为相同的 NSTimeZone (localTimeZone) 我得到“17”作为当前小时.

我还应该提到我正在使用 MTDates增加日期操作,但在我包含这个库之前遇到了这个问题(希望它的包含可能会以某种方式使这些结果更加理智)。话虽这么说,我也尝试用以下内容替换我获取自己的组件的部分:

NSUInteger hours = [current mt_hourOfDay];

不幸的是,这也返回“17”。我希望它返回“23”,但会对“11”感到满意,然后可以将其转换为 24 比例。

最佳答案

您正在使用格式说明符 %lx,它将数字格式化为十六进制值。您希望 %ld 得到十进制(基数 10)。

参见 String Programming Guide对于一些基本的格式说明符。

参见 IEEE spec printf 样式格式说明符的完整列表。 Objective-C 使用此规范并为对象添加了 %@

关于ios - NSDateComponents(通过 MTDates)返回一个奇怪的小时数(mt_hourOfDay),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19721126/

相关文章:

ios - 在 coredata 中保存实体的单行而不是整个实体或上下文

iphone - MGTwittweEngine 没有获取推特页面提要

ios - 更改 UIPageViewController 中点的透明度

iphone - 如何在 iPhone 中取消 ASIFormDataRequest

iphone - 无法理解 iPhone View 布局

ios - canDisplayBannerAds 和飞行模式

ios - becomeFirstResponder 重置其他 View 的 x/y 位置

ios - 速记比较最终太长而无法理解

ios - View 在水平和垂直方向上模棱两可,布局复杂

ios - 用于监控 iBeacon 的更新/刷新率