julianday

function julianday( year, month, day ) --> jd

Description

Converts a Gregorian date to a Julian Day number.

Parameters

year

The year as a number.

month

The month as a number from 1(January) to 12(December).

day

The day as a number from 1 to 31

Return Values

jd

The corresponding julian day for the given gregorian date.

Code

--ZFUNC-julianday-v1
local function julianday( year, month, day ) --> jd
   if year < 0 then year = year + 1 end
   if ( year > 1582 or
      ( year == 1582 and ( month > 10 or
                         ( month == 10 and day >= 15 ) ) ) ) then

      local k = math.ceil( ( month - 14 ) / 12 )
      local a = math.floor( ( year + 4800 + k ) * 365.25 )
      local b = math.floor( ( 367 * ( month - 2 - 12 * k ) ) / 12 )
      local c = math.floor( ( ( year + 4900 + k ) / 100 ) * 0.75 )

      return a + b - c + day - 32075
   elseif ( year < 1582 or
          ( year == 1582 and ( month < 10 or
                             ( month == 10 and day <= 4 ) ) ) ) then

      local k = math.floor( ( 14 - month ) / 12 )
      local a = math.floor( ( 153 * ( month + ( 12 * k ) - 3) + 2 ) / 5 )
      local b = math.floor( ( year + 4800 - k ) * 365.25 )

      return a + b + day - 32083;
   else
      return 0
   end
end

return julianday

Examples

local t = require( "tapered" )
local julianday = require( "julianday" )

-- should work like http://aa.usno.navy.mil/data/docs/JulianDate.php at 12:00:00
t.is( 1721424, julianday( 1, 1, 1 ) )
t.is( 1842713, julianday( 333, 1, 27 ) )
t.is( 2299160, julianday( 1582, 10, 4 ) )

t.is( 2299161, julianday( 1582, 10, 15 ) )
t.is( 2415021, julianday( 1900, 1, 1 ) )
t.is( 2447893, julianday( 1990, 1, 1 ) )

t.is( 2451545, julianday( 2000, 1, 1 ) )
t.is( 2453750, julianday( 2006, 1, 14 ) )
t.is( 2455281, julianday( 2010, 3, 25 ) )
t.is( 2456798, julianday( 2014, 5, 20 ) )

t.done()

See also