如何将格里高利日期转换成等效希伯来日期?
另外,请告诉我这些日历,因为我对这些不太了解。
最佳答案
有一个方便的班级叫做“AA>”。您可以创建这样一个:
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
如果您想将内容转换成更可读的格式,请使用
NSCalendar
: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
好多了!可可不是很棒吗?