Skip to content

Instantly share code, notes, and snippets.

@mshock
Created April 21, 2013 00:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mshock/5427989 to your computer and use it in GitHub Desktop.
Save mshock/5427989 to your computer and use it in GitHub Desktop.
Perl sub converts a Julian date number (JDN) into its Gregorian year, month, day, components not 100% precise for JDN too far in the past, but seems good for modern dates (algorithm & constants from Wikipedia)
# convert julian date number into Gregorian year, month, day parts
# not precise too far in the past... 1580-something?
sub jdn2greg {
my ($jdate) = @_;
# make sure formatted like JDN (DDDDDDD[.D*])
return if $jdate !~ m/^\d{7}\.?(\d*)$/;
# TODO add support for time here based on fractional day RH side of decimal place
# define conversion constants
my $y = 4716;
my $v = 3;
my $j = 1401;
my $m = 2;
my $n = 12;
my $u = 5;
my $s = 153;
my $w = 2;
my $r = 4;
my $B = 274277;
my $p = 1461;
my $C = -38;
# do some math
my $f = $jdate + $j;
$f = $f + $C + int( ( int( ( 4 * $jdate + $B ) / 146097 ) * 3 ) / 4 );
my $e = $r * $f + $v;
my $g = int( ( $e % $p ) / $r );
my $h = $u * $g + $w;
my $day = int( ( $h % $s ) / $u ) + 1;
my $month = ( ( int( $h / $s ) + $m ) % $n ) + 1;
my $year
= int( $e / $p ) - $y + int( ( $n + $m - $month ) / $n );
return ($year, $month, $day);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment