Search code examples
datehijri

Formula of Hijri date


What is the formula of converting "Time since epoch" stamp such as 1525249213 to Hijri date (Year - Month - Day)?

I know there would be one day inaccuracy which is OK for me.


Solution

  • The algorithm I found is to convert the Date to a Julian Date then convert the julian date to Hijri.

    P.S. I can not remember where I found it. I am not responsible for any error or miss-accuracy or an consequence bla bla bla of using this code.

    unsigned long gregorian_to_julian(const int gyear, const int gmonth, const int gday) {
        if (gmonth < 3) {
            gyear -= 1;
            gmonth += 12;
        }
        auto a = int(gyear / 100.0f);
        auto b = (gyear == 1582 && (gmonth > 10 || (gmonth == 10 && gday > 4)) ? -10 :
                  (gyear == 1582 && gmonth == 10 ? 0 :
                   (gyear < 1583 ? 0 : 2 - a + int(a / 4.0f))));
        return int(365.25f * (gyear + 4716)) + int(30.6001f * (gmonth + 1)) + gday + b - 1524;
    }
    
    std::array<int,3> julian_to_hijri(const unsigned long julian_datestamp) {
        std::array<int,3> result;
        auto y = 10631.0f / 30.0f;
        auto epoch_astro = 1948084;
        auto shift1 = 8.01f / 60.0f;
        auto z = julian_day - epoch_astro;
        auto cyc = int(z / 10631.0f);
        z = z - 10631 * cyc;
        auto j = int((z - shift1) / y);
        z = z - int(j * y + shift1);
        result[0] = 30 * cyc + j; //Hijri Year
        result[1]= int((z + 28.5001f) / 29.5f); //Hijri Month
        if (result[1] == 13) {
            result[1]= 12;
        }
        result[2] = z - int(29.5001f * result[1]- 29);// Hijri day
        return result;
    }
    

    P.S. there will be +-1 one day error in the result Hijri date.