Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: how can i find number of days in a given year and month

by Celada (Monk)
on Dec 05, 2005 at 18:36 UTC ( [id://514198]=note: print w/replies, xml ) Need Help??


in reply to how can i find number of days in a given year and month

The mktime has a nice feature which you can exploit for this purpose: you can supply values that are out of range. What happens if you give as input to mktime the zeroth day of this month? Why, you get the last day of last month, of course! mktime is part of your standard C library, so you should get results consistent with everything else on the system, too (that's why I'm not so fond of some of the solutions proposed so far which reimplement the logic).

So the solution is to ask for the zeroth day of the month following the one you are interested in, and see what you get. Also you don't have to worry about what happens in December and you ask for the following month (the 13th month) because mktime deals with that too.

#!/usr/bin/perl use POSIX; ($month, $year) = (12, 2005); $lastday = POSIX::mktime(0,0,0,0,$month-1+1,$year-1900,0,0,-1); @_ = localtime($lastday); print $_[3], "\n";

Note: silly -1+1 used to clarify that we are putting the month into the 0 .. 11 range expected by mktime (-1) and asking for the following month (+1).

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-04-19 13:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found