Gregorian to Hebrew

眉间皱痕 提交于 2019-12-03 21:25:32

问题


How to convert a gregorian date into the equivalent hebrew date? Also please tell about these calendars as I am not having much knowledge of these.


回答1:


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?



来源:https://stackoverflow.com/questions/4644451/gregorian-to-hebrew

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!