开发者

Gregorian to Hebrew

How to convert a gregorian date into the equivalent hebrew date? Also please tell about these calendars as I am not having much knowledg开发者_开发百科e of these.


There's a handy class called NSCalendar. You create one like this:

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

Once you've got the calendar objects, you can use them to convert a date around to various representations:

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

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

On my machine, this logs:

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

If you want to convert stuff to a more readable format, you use 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];

This logs:

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

It would appear that NSDateFormatter is using the gregorian date, but at least it's got the right month name, right?

edit

Actually, I goofed. If you just set the calendar of the NSDateFormatter, you don't have to worry about converting the date at all. See:

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

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

This logs:

hebrew: Shevat 4, 5771

Much better! Isn't Cocoa awesome?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜