Zmanim API Ported to Cocoa / Objective-C

Moshe Berman completed the 2.0 release of his port of the KosherJava Zmanim API from Java to a Cocoa API using Objective-C. You can see the work in the KosherCocoa project page. The original work on the port dates back to Moshe’s iPhone Ultimate Omer 2 (iTunes link) app. In that app, he ported the minimum amount of code needed to calculate sunset in order to roll the day of the Omer after sunset. With Moshe’s latest check-in at github, he provided a port of a good portion of the API sticking to the basic design of the KosherJava API. The complexZmanimCalendar still remains to be ported, but the majority of zmanim in common use are in the ported ZmanimCalendar. Moshe’s blog post Introducing KosherCocoa 2.0 has additional details. Additional developer notes can be seen in the KosherCocoa wiki page. This port will be a boon to iOS developers who now have a simple way to include zmanim in their iPhone and iPad apps.
Here is some sample code that outputs zmanim to the console.

Zmanim.m

#import <Foundation/Foundation.h>
#import "ZmanimCalendar.h"

int main (int argc, const char * argv[]){

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    //  Set up the location
    NSString *locationName = @"Lakewood, NJ";
    double latitude = 40.096; //Lakewood, NJ
    double longitude = -74.222; //Lakewood, NJ
    NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:-18000];

    //  Initialize the Zmanim Calendar
    GeoLocation *geoLocation = [[GeoLocation alloc] initWithName:locationName andLatitude:latitude andLongitude:longitude andTimeZone:timeZone];
    ZmanimCalendar *zmanimCalendar = [[ZmanimCalendar alloc] initWithLocation:geoLocation];

    //  Create a Formatter for the date information
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:timeZone];
    [formatter setDateStyle:NSDateFormatterNoStyle];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];

    NSDate *sunrise = [zmanimCalendar sunrise];
    NSDate *sofZmanShmaMGA = [zmanimCalendar sofZmanShmaMogenAvraham];
    NSDate *sofZmanShmaGRA = [zmanimCalendar sofZmanShmaGra];
    NSDate *sunset = [zmanimCalendar sunset];

    NSLog(@"Today's Zmanim for %@",  [geoLocation locationName]);
    NSLog(@"Sunrise: %@",  [formatter stringFromDate:sunrise]);
    NSLog(@"Sof Zman Shema MGA: %@",  [formatter stringFromDate:sofZmanShmaMGA]);
    NSLog(@"Sof Zman Shema GRA: %@",  [formatter stringFromDate:sofZmanShmaGRA]);
    NSLog(@"Sunset: %@",  [formatter stringFromDate:sunset]);

    [pool drain];
    return 0;
}

This would output (on February 8th):

Today's Zmanim for Lakewood, NJ
Sunrise: 6:58:43 AM
Sof Zman Shema MGA: 8:59:04 AM
Sof Zman Shema GRA: 9:35:04 AM
Sunset: 5:24:09 PM

Calculating Kiddush Levana Times Using the Zmanim API

Crescent Moon
Calculating the earliest and latest times for קידוש לבנה Kiddush Levana has not been part of the KosherJava Zmanim API until now. This is because unlike other zmanim that solely rely on solar calculations that are tied to the Gregorian calendar, times for Kiddush Levanah depend on the Jewish calendar molad (lunar conjunction) computation. With the recent addition of Jewish calendar support to the alpha releases of the KosherJava Zmanim API 1.3, molad calculation was added, allowing for calculation of kidush levana times. Times include the earliest time calculated as 3 and 7 days after the molad. Sof zman kidush levanah includes the מהרי״ל Maharil’s opinion in שו״ת מהרי״ל ס׳ י״ט She’elos Utshuvos Maharil no. 19 that it is calculated as halfway between molad and molad

הטעם הוא משום דאמר בפרק היו בודקין עד שתתמלא פגימתו … וא״כ במילוי תליא מילתא ולאו דווקא ט״ו וי״ו אלא חצי כ״ט י״ב תשצ״ג

and the more lenient full 15 days from the molad mentioned by the Mechaber in the Shulchan Aruch. It should be noted that some opinions hold that the Rema who brings down the opinion of the Maharil’s of calculating halfway between molad and molad is of the opinion that the Mechaber agrees with him. Also see the Aruch Hashulchan. For additional details on the subject, See Rabbi Dovid Heber’s very detailed writeup in Siman Daled (chapter 4) of Shaarei Zmanim.

Calculating the Molad

Kidush levanah times depend on the time of the molad. The time of the molad announced in shuls on Shabbos Mevarchim is the time of the Molad Emtzai (Average Molad) in Yerushalayim local mean time. This has to be converted to standard time. Standard time uses time zones to unify clock times across a large area. With 360° of longitude around the globe, the world is divided into 24 timezones (one per hour) resulting in timezones that are 15° of longitude each. Har Habayis with a longitude of 35.2354° is 5.2354° away from the 30° longitude line. Multiply the 5.235° by 4 minutes per degree (15° of longitude per hour) to reach 20.94 minutes, or 20 minutes and 56.496 seconds (5.235 * 4 = 20.94). This time is subtracted from the local molad time to arrive at Standard time. Since the time of the molad is at the same instant globally (unlike zmanim such as sunrise that depend on a person’s location), converting this to a user’s local time involves simply calculating the time difference between the time in Yerushalayim and your location. If daylight savings time is in use, this has to be added to the calculation. Java date formatting classes do this calculation on Date objects without forcing the developer to do any calculations.

Calculating the Start and End of Kiddush Levana Times

The JewishCalendar class contains the methods for claculating these zmanim. Calculating Tchilas Zman Kiddush Levana (the earliest time Kiddush Levana can be said) is done by adding 3 days or 7 days to the molad time. Sof Zman Kiddush Levana (the latest time Kiddush Levana can be said) is either the time between molad and molad calculated by adding 14 days, 18 hours, 22 minutes and 1.666 seconds to the molad (half the 29 days, 12 hours, 44 minutes and 1 chelek (3.333 seconds)), or by adding 15 days to the molad.

Using the Zmanim API Calculate Molad Based Times

Here is sample code for calculating various kiddush levana times for anywhere in the world for Shevat 5729 (1969). Since formatting classes requires a timezone for proper formatting, the simple code below assumes that you are looking for the time in your local timezone. If you want the time for a timezone other than the one your computer is in, set the SimpleDateFormat.setTimeZone() to the timezone you wish to display the times for.

int year = 5729;
int month = JewishDate.SHEVAT;
Date tchilas3Days = JewishCalendar.getTchilasZmanKidushLevanah3Days(year, month);
Date tchilas7Days = JewishCalendar.getTchilasZmanKidushLevanah7Days(year, month);
Date sofZmanBetweenMoldos = JewishCalendar.getSofZmanKidushLevanahBetweenMoldos(year, month);
Date sofZmanKidushLevanah15Days = JewishCalendar.getSofZmanKidushLevanah15Days(year, month);
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy 'at' HH:mm:ss z");
System.out.println("Tchilas Zman Kiddush Levana 3 Days: " + sdf.format(tchilas3Days));
System.out.println("Tchilas Zman Kiddush Levana 7 Days: " + sdf.format(tchilas7Days));
System.out.println("Sof Zman Kiddush Levana Between Moldos: " + sdf.format(sofZmanBetweenMoldos));
System.out.println("Sof Zman Kiddush Levana 15 Days: " + sdf.format(sofZmanKidushLevanah15Days));

this will output the following in an EST timezone.

Tchilas Zman Kiddush Levana 3 Days: Jan 21, 1969 at 06:06:29 EST
Tchilas Zman Kiddush Levana 7 Days: Jan 25, 1969 at 06:06:29 EST
Sof Zman Kiddush Levana Between Moldos: Feb 02, 1969 at 00:28:31 EST
Sof Zman Kiddush Levana 15 Days: Feb 02, 1969 at 06:06:29 EST

Kiddush Levana Times During Daylight Hours

As you can see, all of these times are at night (After tzais 72 and prior to Alos 72 minutes in Montreal). Many times, these calculations will result in times that are during daylight hours when Kidush Levana can’t be said. When using the API and calculating the time for the tchilas zman kiddush levana and the time is during daylight hours, the earliest time should be tzais the following night. When the calculated time of sof zman kiddush levana is during daylight hours, the time posted should be alos on that morning. The API may at some point support a method of automatically calculating this.

Calculating Erev Pesach Zmanim

MatzosThe Zmanim API did not have dedicated zmanim to claculate the Erev Pesach zmanim of sof zman achilas chametz (the latest time one can eat chametz), and sof zman biur chametz (the latest time to burn chametz) till the April 14 check in to the KosherJava Zmanim Project GitHub repository. The latest time for eating chametz is at the end of the 4th hour of the day. This corresponds to sof zman tfila. The API has about 12 of those, so that does not require any special programming, but to help developers who are unaware of how they work I created 3 wrapper getSofZmanAchilasChametz methods (getSofZmanAchilasChametzGRA(), getSofZmanAchilasChametzMGA72Minutes() and getSofZmanAchilasChametzMGA​16Point1Degrees()) calling the 3 most commonly used getSofZmanTfila methods (getSofZmanTfilaGRA(), getSofZmanTfilaMGA72Minutes() and getSofZmanTfilaMGA​16Point1Degrees()). For example here is the exact code used in getSofZmanAchilasChametzGRA()

public Date getSofZmanAchilasChametzGRA() {
	return getSofZmanTfilaGRA();
}

The API itself is very flexible, and as long as you know the calculation of the zman, you can easily calculate it. For example, to calculate sof zman biur chametz according to the GR"A, the time would be 5 shaos zmaniyos after sunrise. Using the Zmanim API this would be coded as:

Date SofZmanBiurChametzGra = getTimeOffset(getSeaLevelSunrise(), getShaahZmanisGra() * 5);

The exact code used in the API is:

public Date getSofZmanBiurChametzGRA() {
	return getTimeOffset(getSeaLevelSunrise(), getShaahZmanisGra() * 5);
}

Developers who want to use the current API to generate these zmanim can use the following sample as a guide.

String locationName = "Lakewood, NJ";
double latitude = 40.09596; //Lakewood, NJ
double longitude = -74.22213; //Lakewood, NJ
double elevation = 0; //optional elevation
TimeZone timeZone = TimeZone.getTimeZone("America/New_York");
GeoLocation location = new GeoLocation(locationName, latitude, longitude, elevation, timeZone);
ComplexZmanimCalendar czc = new ComplexZmanimCalendar(location);
czc.getCalendar().set(Calendar.YEAR, 2011);
czc.getCalendar().set(Calendar.MONTH, Calendar.APRIL);
czc.getCalendar().set(Calendar.DAY_OF_MONTH, 18);
Date graAchilas = czc.getSofZmanTfilaGRA();
Date graBiur = czc.getTimeOffset(czc.getSeaLevelSunrise(), czc.getShaahZmanisGra() * 5);
Date mga72Achilas = czc.getSofZmanTfilaMGA72Minutes();
Date mga72Biur = czc.getTimeOffset(czc.getAlos72(), czc.getShaahZmanisMGA() * 5);
Date mga16Achilas = czc.getSofZmanTfilaMGA16Point1Degrees();
Date mga16Biur = czc.getTimeOffset(czc.getAlos16Point1Degrees(), czc.getShaahZmanis16Point1Degrees() * 5);
System.out.println("Erev Pesach Zmanim for " + locationName);
System.out.println("Sof Zman Achilas Chametz GRA: " + graAchilas);
System.out.println("Sof Zman Biur Chametz GRA: : " + graBiur);
System.out.println("Sof Zman Achilas Chametz MGA 72 Minutes: " + mga72Achilas);
System.out.println("Sof Zman Biur Chametz MGA 72 Minutes: " + mga72Biur);
System.out.println("Sof Zman Achilas Chametz MGA 16.1 Deg: " + mga16Achilas);
System.out.println("Sof Zman Biur Chametz MGA 16.1 Deg: " + mga16Biur);

this would output

C:\path\to\code>javac ErevPesachZmanim.java

C:\path\to\code>java ErevPesachZmanim

Erev Pesach Zmanim for Lakewood, NJ
Sof Zman Achilas Chametz GRA: Mon Apr 18 10:42:42 EDT 2011
Sof Zman Biur Chametz GRA: : Mon Apr 18 11:49:39 EDT 2011
Sof Zman Achilas Chametz MGA 72 Minutes: Mon Apr 18 10:18:42 EDT 2011
Sof Zman Biur Chametz MGA 72 Minutes: Mon Apr 18 11:37:39 EDT 2011
Sof Zman Achilas Chametz MGA 16.1 Deg: Mon Apr 18 10:13:56 EDT 2011
Sof Zman Biur Chametz MGA 16.1 Deg: Mon Apr 18 11:35:18 EDT 2011

FAQ: How do I Calculate the Jewish/Hebrew Date for …?

Sunrise Calendar

This FAQ is now obsolete. Jewish Calendar Calculations are now supported. See the Zmanim API 1.3.0 Release announcement

Question:

How do I get the Jewish Date for … using the Zmanim API?

Answer:

The current version of the Zanim API does not support Jewish calendrical calculations. Zmanim are almost exclusively based on the solar calendar, so for example, the sunrise on February 8th this year in Montreal (or any other date and location), will be almost the same every year. for this reason there was little point (as far as zmanim) to support Jewish date calculations in the API. One of the only zmanim to rely on a Jewish date is the sof zman kidush levanah calculation, though there are some opinions that it is purely molad based, and this can be calculated without a Jewish calendar component to the API. This zman is obviously not currently implemented in the Zmanim API. I am currently working on adding Jewish date support to the API. The code is based off Avrom Finkelstein‘s no longer active HebrewDate project. I refactored a lot of the code and fixed a number of bugs. Anyone interested in alpha testing this code can download the latest Zmanim SVN code.
I mentioned that it “will be almost the same every year” and this is due the approximate 1/4 day drift between the 356 day calendar year and the approximately 365.25 days actually present in the astronomical year, a discrepancy corrected every leap year. A future FAQ (probably a few of them) may delve specifically into this drift as well as general zmanim accuracy issues in detail.
If you are simply looking to convert a Hebrew date to Gregorian or Gregorian to Hebrew online without the API, try the JewishGen calendar conversion tools.

FAQ: Why Some Zmanim Never Occur (Developers Beware)

Question:

Why do some zmanim never occur in some locations? Developers Beware!

Answer:

While most people realize that the sun may not rise or set in the Arctic and Antarctic Circles (see the Rabbi Dovid Heber’s article When Does One Pray When There Is No Day in the Star-K’s Kashrus Kurrents), many are not aware that some twilight dips will not occur during part of the year as far south of the Arctic Circle as London. For example around the summer solstice in London (on the zmanim map) the sun will never dip far enough below the horizon to reach alos 16°. This happens in London from June 4th through July 8th. The image seen on the top right (original at timeanddate.com) shows various civil twilights centered on London on Midnight June 21st. Look carefully to see the various bands of twilight. Gateshead will not have alos 16° from May 16th through July 28th, while Anchorage, Alaska (yes there is a Frum Shul in Anchorage with an interesting davening direction issue that is discussed in the Davening Direction from Alaska post ) will not have alos 16.1° from April 25th to August 20th. Zmanim based on sunrise such as alos 72 that is a 72 minute offset of sunrise can be calculated as long as sunrise can be calculated, something that will happen as long as you are not in the Arctic or Antarctic Circles.
For this reason, the Zmanim API will return a null when a zman will not happen. A Long.MIN_VALUE will be returned when a long is expected such as in the case of a shaah zmanis. While an inconvenience to developers who have to code for this, the alternative of a default date would mean that developers unaware of this would return incorrect zmanim, something far worse than a program error from a NullPointerException.
In recent weeks two publicly available programs using the Zmanim API ran into issues due to nulls returned for early alos times. Being something not anticipated by the developers, the nulls generated errors in the programs that quickly led to fixes. For this reason, Yitzchok updated the Zmanim .NET project to return the nullable DateTime? instead of the regular DateTime that it had previously been returning. While the Zmanim API documentation always made the possibility of a null being returned possible, I modified the documentation to make this clear on the return value documentation for every zman. Code with the modified documentation was part of the recently released Zmanim API 1.2.1.