2013-07-26 119 views
0

由於時區問題,我陷入了NSDateNSDateFormatter的某處。將任何日期轉換爲本地日期問題

我需要發送時間到服務器只有UTC(它被轉換爲unix時間)。

這裏是我的幾步我在做什麼:

  1. 選擇從壓延日期應與當前時間被加入,並轉換爲UTC。

  2. 將選定日期與當前日期進行比較。只需知道選定的日期是過去還是未來的日期。 (根據過去/未來/當前日期,很少有其他操作要完成)。

我曾嘗試這樣的代碼:對NSDate

在類別:

-(NSDate *) toLocalTime{ 
    NSDate* sourceDate = self; 
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithName:@"UTC"]; 
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone]; 

    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate]; 
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate]; 
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset; 

    NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate]; 

    return destinationDate; 
} 

但是當我嘗試日期轉換爲本地,(有時存在的問題,我不知道當前時間是否在當地時區)。如果他們在UTC,那麼上述方法工作正常。

如果時間已經在本地時區,那麼它再次增加了interval,我得到的時間不正確。

我出於主意,請幫助我。

任何想法將不勝感激。

+0

我希望它能幫助你,請參考這個鏈接。 http://stackoverflow.com/questions/7362199/iphone-correct-way-for-getting-current-date-and-time-for-a-given-place-timez – Romance

+0

除非你絕對知道你'在做,你應該總是安排一個NSDate對象來表示UTC。如果您使用NSDateFormatter,設置爲本地時區,要將字符串轉換爲NSDate,則會生成UTC日期 - 不需要「fudging」。要將字符串值從一個時區轉換爲另一個時區,最安全/最簡單的方法是將兩個日期格式化程序設置爲兩個不同的時區,然後簡單地轉換爲NSDate並返回。 –

+0

「(有時我不確定當前時間是否在本地時區內)」 - 由[NSDate date]提供的「當前時間」是* always * UTC(除非有人已經將時鐘在手機上,在這種情況下,他們得到他們應得的)。 –

回答

1

NSDate表示1970年1月1日以來的UTC時間。永遠不要試圖假裝它是別的。千萬不要試圖將NSDate視爲的特定當地時間。

因此,您需要的是日曆+日期的偏移量,代表自今天午夜以來的時間。

要獲得今天UTC 0:00 UTC,您首先需要公曆時區的公曆。

NSTimeZone* utcTimeZone = [NSTimeZone timeZoneWithName:@"UTC"]; 
NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar]; 
[gregorian setTimeZone: utcTimeZone]; 

現在您使用最新組件獲得自午夜UTC的小時,分​​鍾和秒

NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; 
NSDate *date = [NSDate date]; 
NSDateComponents *comps = [gregorian components: unitFlags fromDate:date]; 

如果您是從您的日曆上的日期午夜(UTC)的日期,你可以得到午夜UTC +你的小時,分​​鍾和秒這樣:

NSDate* theDateIWant = [gregorian dateByAddingComponents: comps 
               toDate: midnightUTCDateFromCalendar 
               options: 0]; 
NSLog(@"The final date is %@", theDateIWant);