格里高利到希伯来语

时间:2011-01-10 07:07:40

标签: iphone objective-c gregorian-calendar

如何将格里高利日期转换为等效的希伯来日期? 另外请告诉我们这些日历,因为我对这些日历知之甚少。

1 个答案:

答案 0 :(得分:13)

有一个名为NSCalendar的便捷课程。你创建一个这样的:

NSCalendar * gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendar * hebrew = [[NSCalendar alloc] initWithCalendarIdentifier:NSHebrewCalendar];

获得日历对象后,您可以使用它们将日期转换为各种表示形式:

NSDate * date = [NSDate date];
NSDateComponents * components = [gregorian components:NSUIntegerMax fromDate:date];
NSDate * hebrewDate = [hebrew dateFromComponents:components];

NSLog(@"date: %@", date);
NSLog(@"hebrew: %@", hebrewDate);

在我的机器上,这会记录:

date: 2011-01-09 23:20:39 -0800
hebrew: 1751-09-25 23:20:39 -0800

如果您想将内容转换为更易阅读的格式,请使用NSDateFormatter

NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterLongStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
[formatter setCalendar:gregorian]; //this is usually unnecessary; it's here for clarity

NSLog(@"date: %@", [formatter stringFromDate:date]);

[formatter setCalendar:hebrew];

NSLog(@"hebrew: %@", [formatter stringFromDate:hebrewDate]);
[formatter release];

此日志:

date: January 9, 2011
hebrew: Tishri 9, 2011

似乎NSDateFormatter正在使用格里高利日期,但至少它有正确的月份名称,对吧?

修改

实际上,我傻了。如果您只设置NSDateFormatter的日历,则无需担心转换日期。参见:

NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterLongStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
[formatter setCalendar:hebrew];

NSLog(@"hebrew: %@", [formatter stringFromDate:[NSDate date]]);
[formatter release];

此日志:

hebrew: Shevat 4, 5771

好多了!可可不是很棒?