我正在使用此方法将月份和年份转换为等于给定年份中最后一天的日期。从核心数据检索NSDate时发生的时区问题
+ (NSDate*)endOfMonthDateForMonth:(int)month year:(int)year
{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.year = year;
comps.month = month;
NSDate *monthYearDate = [calendar dateFromComponents:comps];
// daysRange.length will contain the number of the last day of the endMonth:
NSRange daysRange = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:monthYearDate];
comps.day = daysRange.length;
comps.hour = 0;
comps.minute = 0;
comps.second = 0;
[comps setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[calendar setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[calendar setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
NSDate *endDate = [calendar dateFromComponents:comps];
return endDate;
}
我想要的日期有时间是00:00:00成分,这就是为什么我已经设置了时区GMT 0和几分钟,几小时日期组件和秒0的返回日期从该方法是正确的,并具有从00:00:00的时间组件。
这是我如何保存日期到核心数据:
NSDate *endDate = [IBEstPeriod endOfMonthDateForMonth:endMonth year:endCalYear];
[annualPeriod setEndDate:endDate];
检索数据,并将其NSLogging调试器控制台后,我得到的日期一样2008-12-30 23:00:00 +0000
与时间分量= 0
为什么组件现在改变了? 不应该停留在00:00:00吗?
这里我错了什么?
谢谢!
我试过你的代码,但我仍然有同样的问题:我得到'2010-12-30 23:00:00 +0000 '而不是'2010-12-31'。 – AlexR 2012-07-10 16:20:22
你确定你没有在其他地方更改日期吗?我只是更新了我的答案,以显示我在运行时收到的实际结果。 – lnafziger 2012-07-10 16:31:56
有没有可能我需要设置不同的本地时区(我在本地时区(GMT +2 =德国),但在创建日期时使用了GMT + 0。 – AlexR 2012-07-10 16:37:13