【发布时间】:2016-03-15 21:27:38
【问题描述】:
我试图在 NSDate 中存储日期,但没有得到正确的输出。 下面写代码sn-p。
NSDate *firstDate = [NSDate dateWithYear:2015 month:12 day:1 ];
预计输出为 2015-12-1 18:30:00 +0000。
但是得到 2015-11-30 18:30:00 +0000
忽略时间戳。
dateWithYear:month:day 是我正在使用的第 3 方日历中的分类方法。该方法的代码如下:
+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [NSDate componentsWithYear:year month:month day:day];
return [calendar dateFromComponents:components];
}
return [calendar dateFromComponents:components];
是
+ (NSDateComponents *)componentsWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:year];
[components setMonth:month];
[components setDay:day];
return components;
}
提前致谢。
【问题讨论】:
-
为什么期望它是世界标准时间下午 6.30?你是怎么得到输出的?我怀疑它只是在您当地时区的午夜创建一个日期。如果该时区位于 UTC+05:30,那么这将解释您的输出。
-
乔恩忽略时间。如何获得我作为输入给出的确切日期。我需要设置时区吗?
-
“忽略时间”毫无意义——它实际上是价值的一部分。
NSDate只是一个时间点,您指定的代码代表时间点,即您当前时区指定日期的午夜。您想要它代表的确切时间点是什么? (dateWithYear指定在哪里?我在documentation 中看不到它...) -
真正的问题是,您使用的
dateWithYear:month:day方法是什么?这不是标准的NSDate方法。它在NSCalendar上也不存在,它具有从组件值创建日期的便捷方法。如果没有看到这个方法的代码,就不可能说它会返回什么。
标签: timezone nsdate ios9 nstimezone