我正在使用此方法將月份和年份轉換爲等於給定年份中最後一天的日期。從核心數據檢索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