2013-04-24 85 views
0

destinationDate和組件的結果不同。 我該如何解決這個問題?NSDate轉換NSDateComponents問題

NSTimeZone* sourceTimeZone  = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; 
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone]; 

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

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

NSCalendar *calendar   = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 

NSDateComponents *components = [calendar components:(NSYearCalendarUnit | 
                 NSMonthCalendarUnit | 
                 NSDayCalendarUnit | 
                 NSHourCalendarUnit | 
                 NSMinuteCalendarUnit| 
                 NSSecondCalendarUnit) fromDate:destinationDate]; 

NSLog(@"%@", destinationDate); 
NSLog(@"%@", components); 

2013年4月24日19時27分09秒+0000

日曆年份:2013 月:4 閏月:沒有 日:25 小時:4 分:27 第二:9

+0

你是什麼問題就在這裏,日期的說明會始終處於GMT。它看起來像是你的localTimeZone比GMT落後5個小時。第一個日誌可以解釋爲4:27 PM,它與組件 – Anupdas 2013-04-24 10:38:24

+0

中顯示的相同,你是否已經得到了答案。 – Balu 2013-04-24 11:19:52

回答

1

NSDateComponents總是以格林尼治標準時間格式給出日期,所以只需簡單地放置在下面就可以獲得當前日期。

NSDateComponents *components = [calendar components:(NSYearCalendarUnit | 
                  NSMonthCalendarUnit | 
                  NSDayCalendarUnit | 
                  NSHourCalendarUnit | 
                  NSMinuteCalendarUnit| 
                  NSSecondCalendarUnit) fromDate:[NSDate date]]; 

替換destinationDate[NSDate date]

輸出:

2013-04-24 16:05:08 +0000 

<NSDateComponents: 0x7e3e5b0> 
    Calendar Year: 2013 
    Month: 4 
    Day: 24 
    Hour: 16 
    Minute: 5 
    Second: 8 
+0

你是如何得出OP想要的? – Anupdas 2013-04-24 10:48:19

+0

他規定destinationDate和組件不同,這就是爲什麼我找到他的代碼中的問題。 – Balu 2013-04-24 10:49:42

+0

在他的代碼中,他正在創建一個sourceDate作爲currentDate,並使用間隔來創建一個destinationDate,這取決於timeZone將被提前或延遲。這個問題本身非常模糊,你爲什麼說要用currentDate替換destinationDate。很混亂。 – Anupdas 2013-04-24 10:53:48

3

的日期(destinationDate)被印刷在GMT。但是,日期組件不是因爲日曆是使用本地時區創建的。

如果您使用calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]進行測試,您將獲得兩者的相同結果。否則,你會得到差異兩次(第一次由你的代碼,第二次由日曆)

其實,你的代碼沒有多大意義。不應該由時區修改NSDate,因爲它不包含任何時區信息。 A NSDate始終代表GMT格式的日期。僅在要將其轉換爲字符串時才轉換日期 - 如果要這樣做,請在使用NSCalendarNSDateFormatter時設置正確的時區。

下面的代碼足以打印出與系統(默認值)時區的日期,

NSDate* sourceDate    = [NSDate date]; 
NSCalendar *calendar   = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 

NSDateComponents *components = [calendar components:(NSYearCalendarUnit | 
                NSMonthCalendarUnit | 
                NSDayCalendarUnit | 
                NSHourCalendarUnit | 
                NSMinuteCalendarUnit| 
                NSSecondCalendarUnit) fromDate:destinationDate]; 

NSLog(@"%@", sourceDate); 
NSLog(@"%@", components);