Julian Date Function

Computing the JD (Julian Date) corresponding to a given date and time is fundamental to many astronomical and general calendrical computations. The JD value serves as the independent time variable corresponding to the moment to which the computation applies.

PHP has native built-in Julian Day Number and inverse Julian Day Number functions which makes date computations much easier.  However, the native functions do not take into account the time of day.

This custom Julian Date function returns the full Julian Date value corresponding to any given date and time on the Julian or Gregorian calendar.


Go to:  START  |  PROGRAMS INDEX  |  Inverse Julian Date Function


The following PHP function will compute the JD (Julian Date) for any given moment on the Julian or Gregorian calendars.

/*
   ------------------------------------------------------------------
   This function takes a Julian or Gregorian calendar date, time and
   calendar mode arguments and returns the corresponding Julian Date.

   Julian Calendar Origin
   BC 4713-Jan-01-Mon = JD Number 0

   Gregorian Calendar Origin
   BC 4714-Nov-24-Mon = JD Number 0

   Yn = Year Number     (-4714 to 9999) (Negative Year = BC)
   Mn = Month Number        (1 to 12)
   Dn = Day of Month Number (1 to 31)

   hh = hours
   mm = minutes
   ss = seconds (with optional decimal fraction)

   CalMode = 'J' for Julian or 'G' for Gregorian = Default

   Returns Julian Date (JD) rounded to 16 decimals.

   ON ERROR:
   Returns FALSE if any non-numeric date or time arguments.
   ------------------------------------------------------------------
*/

   function Julian_Date ($Yn,$Mn,$Dn, $hh=0,$mm=0,$ss=0, $CalMode='G')
{
   $Q = 48; // Set internal working decimals precision.

// Read input arguments.
   $Y  = trim($Yn);
   $m  = trim($Mn);
   $d  = trim($Dn);
   $hh = trim($hh); if ($hh == '') {$hh=0;}
   $mm = trim($mm); if ($mm == '') {$mm=0;}
   $ss = trim($ss); if ($ss == '') {$ss=0;}

// Apply non-numeric input error filters.
   if(!Is_Numeric($hh) or !Is_Numeric($mm) or !Is_Numeric($ss)){return FALSE;}
   if(!Is_Numeric($Y)  or !Is_Numeric($m)  or !Is_Numeric($d)) {return FALSE;}

// Compute JD Number for calendar date according to calendar mode.
// If not Julian, then Gregorian, by default.
   $JDNum = (substr(StrToUpper(trim($CalMode)),0,1) == 'J')?
             JulianToJD($m,$d,$Y) : GregorianToJD($m,$d,$Y);

// Compute full Julian Date for date and time.
   $JD = bcAdd(bcSub($JDNum,'0.5',$Q),
         bcDiv(bcAdd(bcAdd(bcMul('3600',$hh,$Q),
         bcMul('60',$mm,$Q),$Q),$ss,$Q),'86400',$Q),$Q);

// Round off final JD value at 16 decimals and then
// trim off any redundant zeros or decimal point.
   $JD = RTrim(RTrim(bcAdd($JD, '0.00000000000000005', 16), '0'), '.');

// Done.
   return $JD;
}

There is one tiny glitch in the program in that if fails when JD = 0.0