2010-04-27 20 views
6

我試圖在公元前時代創造一個日期,但是失敗相當困難。下面的年份返回'4713',而不是'-4712':如何在遙遠的過去創建一個特定的日期,BC時代

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    NSDateComponents *components = [NSDateComponents new]; 
    [components setYear: -4712]; 
    NSDate *date = [calendar dateFromComponents:components]; 
    NSLog(@"%d", [[calendar components:NSYearCalendarUnit fromDate: date] year]); 

任何想法我做錯了什麼?

UPDATE:工作代碼

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    NSDateComponents *components = [NSDateComponents new]; 
    [components setYear: -4712]; 
    NSDate *date = [calendar dateFromComponents:components]; 
    NSDateComponents *newComponents = [calendar components:NSEraCalendarUnit|NSYearCalendarUnit fromDate:date]; 
    NSLog(@"Era: %d, year %d", [newComponents era], [newComponents year]); 

這就爲時代打印0,正如本解釋。

回答

6

你的代碼實際上工作正常。由於沒有零年,所以-4712是公元前4713年。如果你檢查時代組件,你會發現它是零,在公曆中表示BC。翻轉負號,你會看到公元4712年(時代1)。

+0

我知道我錯過了一塊拼圖:)非常感謝! (增加了代碼的更新版本) – alloy 2010-04-27 14:14:02

相關問題