简体   繁体   English

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

[英]iOS - Create NSDate without hours/minutes and ignoring daylight saving shifts

I'm trying to remove hours and minutes from my NSDate object 我正在尝试从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]];

and it works fine until April 2013, after that my NSDate objects are created with -1 hour shift. 并且可以正常工作到2013年4月,之后我的NSDate对象将以-1小时的班次创建。 I'm pretty sure it is because daylight saving time. 我很确定这是因为夏时制。

How can I make my NSDate objects be 00:00:00 +0000 during all year ? 我如何使我的NSDate对象在全年中都为00:00:00 +0000?

NSDate objects are inherently stored as GMT values. NSDate对象固有地存储为GMT值。 The problem you're running into here is that you're doing calculations using the currentCalendar (which might be in DST at the moment) and the localTimeZone secondsFromGMT, which switches depending on the time of year. 您在这里遇到的问题是,您正在使用currentCalendar(当前可能在DST中)和localTimeZone secondsFromGMT进行计算,具体取决于一年中的时间。

The best solution here is to use an NSCalendar that is GMT instead of based on a timezone that shifts, if (as you indicate) you want them to be +0000 at all times. 最好的解决方案是使用GMT的NSCalendar,而不是根据时区变化,如果(如您所指出的)您希望它们始终都为+0000。

Alternatively, you can change to use NSTimeZone 's secondsFromGMTForDate: which takes into account DST at the date/time in question. 或者,你可以改变使用NSTimeZonesecondsFromGMTForDate:它考虑DST在有关日期/时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM