2010-10-07 182 views
0

我已經嘗試了幾個帖子的解決方案,但沒有運氣。 問題是我面臨的可能是白色時區。在設備和模擬器上,UIDatePicker和NSDateFormatter都返回不正確的日期,從所選日期(根據設備或mac上設置的當前時區)添加或減去GMT 0之間的差異。UIDatePicker&NSDateFormatter返回不正確的日期

我已經試過設置區域和時區,但沒有任何工作。 任何想法都很好!謝謝。

(還沒有發佈任何代碼示例,因爲兩者都沒有,現在設置的任何屬性初始化)。

更新1:

這裏是代碼片段:

datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, frame.size.height - 216.0, frame.size.width, 216.0)]; 

    [self addSubview:datePicker]; 

    .... 


    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 

    [formatter setDateFormat:@"EEE, MMM d, y h:mma"]; 

    NSString *dateString = [formatter stringFromDate:datePicker.date]; 
    [formatter release]; 
+0

發佈您的代碼。幫助我們幫助你! ;-) – 2010-10-07 17:39:37

回答

14

發現解決方案時,應按以下方式添加時區差異。

- (NSDate *)dateToGMT:(NSDate *)sourceDate { 
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone]; 
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate]; 
    NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:destinationGMTOffset sinceDate:sourceDate] autorelease]; 
    return destinationDate; 
} 
+0

ios9.2的工作代碼。 – pkc456 2016-01-06 06:42:48

0

你說你設定時區,但你沒有說在哪裏。你需要設置你的UIDatePicker和NSDateFormatter的timeZone屬性。

+0

我已經用代碼更新了最初的帖子。我試圖將timeZone屬性設置爲:defaultTimeZone,localTimeZone,甚至指定GMT + 3,但他們仍然返回不正確的日期。 – 2010-10-08 06:15:25

相關問題