当iOS设置中的日历是日语或佛教时,如何显示NSDate的公历年

时间:2013-10-07 19:11:48

标签: ios objective-c nsdate nsdateformatter

我试图在日历设置为日语时显示NSDate的4位数格里高利年。

NSLog(@"Date joined: %@", self.dateJoined);
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.calendar = calendar;
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
formatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"EST"];
formatter.dateFormat = @"yyyy";
NSLog(@"Year joined: %@", [formatter stringFromDate:self.dateJoined]);

日志:

Date joined: 2012-05-29 22:13:54 +0000
Year joined: 4000

我做错了什么?

1 个答案:

答案 0 :(得分:0)

试试这个。它有效。

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

NSDateComponents *dateComps = [cal components:(NSYearCalendarUnit) fromDate:self. dateJoined];

NSLog(@"date = %d",[dateComps year]);

// IGNORE IF USING ARC
[cal release];