Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Useful Date Algorithms

by Sol-Invictus (Scribe)
on Jan 27, 2004 at 21:37 UTC ( [id://324540]=CUFP: print w/replies, xml ) Need Help??

Date calculations : yes there are modules for this on CPAN, but wouldn't you like to know how to do this kind of stuff :)

Some algorithms useful for calculating:

  • leap years
  • the day of the week a given dates fell on
    (but bear in mind the exact dates when countries started changing from Julian to Gregorian vary, more info here).
#!/usr/bin/perl -w #=========== declare includes ============= use strict; use diagnostics-verbose; #========== declare variables ============= my($Adjuster,$GregorianDay,$JulianDay,$LastOfMonth,$day,$month,$year); my(@DaysOfWeek); # Need to print out calendar for a given year? # 30 days hath September, April, June and November # all the rest have 31 # except February 28 days clear, 29 each leap year # the rule for working out leap years = # If the year is divisible by 100 it's NOT a leap year # If the year is divisible by 4 or 400 it's a leap year $LastOfMonth = '30'if ($month == (4||6||9||11)); $LastOfMonth = '31'if ($month == (1||4||5||7||8||10||12) ); if ($month == 2){ if ( $year % 100 != 0 && $year % 4 == 0 || $year % 400 == 0 ){ $LastOfMonth = '29'; } else { $LastOfMonth = '28'; } } # The programmatic way to convert the date into the name for the day o +f the date given # this script expects to be fed the date, which it will then output a +number # which represents Julian day and Gregorian day with Sunday=0 # Julian days are useful for calculating dates before the change to th +e Gregorian Calendar $day= 1; $month=3; $year=2003; $Adjuster = int ( ( 14-$month )/12 ); $month = int ( $month +( ( $Adjuster*12 )-2 ) ); $year = int ( ( $year -$Adjuster ) ); $JulianDay = (5+$day+$year+int($year/4)+int(31*$month/12) ) %7; $GregorianDay = ($day + $year + int($year/4) - int($year/100) + int($y +ear/400) +int (31*$month/12) ) %7; print "The value of \$JulianDay is: ",$JulianDay,"\n"; print "The value of \$GregorianDay is: ",$GregorianDay,"\n"; # use the value output on an array like this to get the day of the wee +k @DaysOfWeek=qw( Sunday Monday Tuesday Wednesday Thursday Friday Saturday );

Replies are listed 'Best First'.
A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://324540]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2024-03-28 12:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found