iOS - 创建没有小时/分钟的NSDate并忽略夏令时转换

Ole*_*leg 4 iphone cocoa-touch objective-c ios

我正试图从我的NSDate对象中删除小时和分钟

keyDate = [[array objectAtIndex:i] date];
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];

NSDateComponents* components = [calendar components:flags fromDate:keyDate];
keyDate = [[calendar dateFromComponents:components] dateByAddingTimeInterval:[[NSTimeZone localTimeZone]secondsFromGMT]];
Run Code Online (Sandbox Code Playgroud)

它工作正常,直到2013年4月,之后我的NSDate对象创建为-1小时轮班.我很确定这是因为夏令时.

如何NSDate在一年中将我的物品设为00:00:00 +0000?

gai*_*ige 6

NSDate对象固有地存储为GMT值.你在这里遇到的问题是你正在使用currentCalendar(目前可能在DST中)和localTimeZone secondsFromGMT进行计算,后者根据一年中的时间进行切换.

这里最好的解决方案是使用GMT的NSCalendar而不是基于移动的时区,如果(如您所示),您希望它们始终为+0000.

或者,您可以更改为使用在相关日期/时间考虑夏令时的NSTimeZone's secondsFromGMTForDate:.