2015-01-15 285 views
2

請幫我不明顯代碼的行爲日期格式不正確?

NSCalendar *calendar = [NSCalendar currentCalendar]; 

NSDateComponents *dateComponents = [[NSDateComponents alloc] init]; 
dateComponents.hour  = 15; 
dateComponents.minute = 20; 
dateComponents.calendar = calendar; 

NSDate * endDate = [calendar dateFromComponents:dateComponents]; 

結束日期爲0001-01-01 12點49分43秒+0000。爲什麼?

由於時區不同,小時值可能不正確。爲什麼這樣奇怪的分鐘和秒鐘值? 此致敬禮。

+2

如果我不得不猜測,我會說這是由01/01/0001以來日曆中積累的閏秒造成的,所以我會嘗試設置年份。但我只是做了這個,所以這可能是完全錯誤的。 –

+0

有趣的...你可以打印日曆的時區屬性,特別是屬性。 'secondsFromGMT'和'abbreviation'。 –

+0

@GuillaumeAlgis好主意! –

回答

1

如果我們只考慮下面的代碼片段

NSCalendar *calendar = [NSCalendar currentCalendar];   
NSDateComponents *components = [[NSDateComponents alloc] init]; 
[components setCalendar:calendar]; 
NSDate *date = [calendar dateFromComponents:components]; 

date = 0000-12-31 23:06:32 +0000,因爲:

日曆中 封裝有關的清算時間系統的信息一個開端,長度和的分歧年定義。

[...]

當有提供完全指定絕對時間不夠分量,日曆使用其選擇的默認值。 Apple Documentation

一個NSDateComponents對象是沒有意義的本身;你需要知道它被解釋的日曆,你需要知道這些值是單位的絕對值還是單位的數量。 Apple Documentation

其實,一切都很好,正是文檔所說的。

+1

我們閱讀了文檔,但實際上它存在疑問。謝謝。 –