I am attempting to write a function to calculate a user's Chinese zodiac sign based on his or her birthday for Drupal.
I originally had a function for calculating based on the Gregorian calendar (1924 = Rat, 1925 = Ox). This was easy to write, but several of my users have complained that the Chinese zodiac is actually based on the lunar calendar, and a list of relevant start and end dates can be found here.
I started writing the code as follows. The big problem is that I have an if
, else if
, and else
per year, and at this rate I will have to manually code 100 years worth of birthdays. On the other hand, I'm unsure of how to use a loop to iterate over this, because the day the lunar year starts and ends each year is different. Any insight on how to make this more efficient would be highly appreciated.
function mymodule_calculate_chinese_zodiac($birthdate) {
// Drupal MySQL data looks like this: 1981-07-30 00:00:00
$year = substr($birthdate, 0, 4);
$month = substr($birthdate, 5, 2);
$day = substr($birthdate, 8, 2);
if ($year == 1924) {
if ($month > 2) {
// Rat
$sign = "1";
}
else if (($month == 2) && ($day > 4) {
$sign = "1";
}
else {
// Pig
$sign = "12";
}
}
else if ($year == 1925) {
if ($month > 1) {
// Ox
$sign = "2";
}
else if (($month == 1) && ($day > 23)) {
$sign = "2";
}
else {
$sign = "1";
}
}
else if ($year == 1926) {
if ($month > 2) {
// Tiger
$sign = "3";
}
else if ($month == 2) && ($day > 12) {
$sign = "3";
}
else {
$sign = "2";
}
}
//All years until 2020
return $sign;
}