2013-04-18 30 views
2

我想從兩個日期之間添加的核心數據中檢索所有條目。我正在使用NSPredicate。由於我沒有得到正確的結果,我試着記錄日期。它顯示了以前的日期。谷歌搜索了一段時間之後,我添加了NSLog顯示以前的日期

[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];我的code.Now,它顯示正確的日期,但結果仍然是錯誤的。

這是我使用的代碼。

NSDate *fromDate = [[self dateFormatter]dateFromString:self.fromDateField.text]; 
NSLog(@"%@",fromDate); 
NSDate *toDate = [[self dateFormatter]dateFromString:self.toDateField.text]; 
NSLog(@"%@",toDate); 
NSComparisonResult result = [fromDate compare:toDate]; 
switch (result) { 
    case NSOrderedAscending: 
    { 
     //code 
    } 

- (NSDateFormatter *)dateFormatter 
{ 
static NSDateFormatter *dateFormatter = nil; 
if (dateFormatter == nil) 
{ 
    dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; 
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle]; 
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 
} 
    return dateFormatter; 
} 

在此先感謝

回答

1

如果你登錄一個NSDate對象直接,它會永遠顯示GMT/UTC時區的大部頭。您必須記錄日期格式化程序的輸出。

NSLog(@"%@",[self.dateFormatter stringFromDate:toDate]); 

這將需要您的時區帳戶。或者更好:dateformatter日曆的時區 - 如果您不更改該設備,則默認設備是什麼。

+0

是的,他們正在顯示正確的日期now.then爲什麼我得到錯誤的結果? – Sekhar

+0

您沒有收到錯誤的結果:內部日期始終保存在UTC時區中。就這些。但是日曆知道,即在UTC時間的哪個時間,您的時區的一天開始,凝灰岩就像那樣。實際上,一個日期只是一個時間,除了秒鐘之後。只有在日曆內纔會變得有意義,因爲日曆定義了日,月,年和時分。 – vikingosegundo

+0

所以不要設置時區。將其留給設備。 – vikingosegundo