Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: How to subtract date by 1 day

by cosmicperl (Chaplain)
on Dec 13, 2007 at 15:53 UTC ( [id://656846]=note: print w/replies, xml ) Need Help??


in reply to How to subtract date by 1 day

I tend to use a couple of routines I wrote. They take leap years into account, and expect the date to be passed in as YYYYMMDD

sub DateNext { my ($y, $m, $d) = unpack('a4a2a2', $_[0]); my @daysinmonth = ("31","28","31","30","31","30","31","31","30","31" +,"30","31"); my @daysinmonthly = ("31","29","31","30","31","30","31","31","30","3 +1","30","31"); $d++; if (($y % 4) == 0) { if ($d > @daysinmonthly[$m - 1]) { $m++; if ($m > 12) { $m = 1; $y++; } ## End if $d = 1; } ## End if } ## End if else { if ($d > @daysinmonth[$m - 1]) { $m++; if ($m > 12) { $m = 1; $y++; } ## End if $d = 1; } ## End if } ## End else my $returndate = sprintf("%04d%02d%02d",$y,$m,$d); return $returndate; } ## End sub ### Brings date to the previous day sub DatePrevious { my ($y, $m, $d) = unpack('a4a2a2', $_[0]); my @daysinmonth = ("31","28","31","30","31","30","31","31","30","31" +,"30","31"); my @daysinmonthly = ("31","29","31","30","31","30","31","31","30","3 +1","30","31"); $d--; if (($y % 4) == 0) { if ($d < 1) { $m--; if ($m < 1) { $m = 12; $y--; } ## End if $d = @daysinmonthly[$m - 1]; } ## End if } ## End if else { if ($d < 1) { $m--; if ($m < 1) { $m = 12; $y--; } ## End if $d = @daysinmonth[$m - 1]; } ## End if } ## End else my $returndate = sprintf("%04d%02d%02d",$y,$m,$d); return $returndate; } ## End sub


Lyle

Replies are listed 'Best First'.
Re^2: How to subtract date by 1 day
by KurtSchwind (Chaplain) on Dec 13, 2007 at 16:14 UTC

    Actually, there is a flaw in your Leap_year logic. (This is why people who write date routines pull out their hair).

    A leap year is a year that is divisible by 4, but not by 100, unless it's divisible by 400. Not that your solution is likely to encouter the bug anytime soon. But the year 2100 is NOT a ly.

    --
    I used to drive a Heisenbergmobile, but every time I looked at the speedometer, I got lost.
Re^2: How to subtract date by 1 day
by Anonymous Monk on Apr 08, 2020 at 12:51 UTC
    Leap year evaluation condition need to be updated-
    (((($y%4) == 0) && (($y%100) !=0)) || (($y%400) ==0) )

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2024-04-25 19:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found