views:

469

answers:

5

Previously, this function worked for me...

$this_day = Day_of_Week($lyear, $month, $day);

using this lib..

use Date::Calc qw(Add_Delta_Days Day_of_Week Delta_Days);

But I need another way to get this same info.

the error it returned is

Date::Calc::Day_of_Week(): not a valid date

Any ideas?

+2  A: 
use Posix qw(mktime);
my $epoch = mktime(sec, min, hour, mday, mon, year);
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($epoch);
heeen
I forget - is the day of the week based on 0 or 1?
Paul Tomblin
Based on 0. Use qw(Sunday Monday Tuesday Wednesday Thursday Friday Saturday) to translate $wday to the day of the week.
Chris Lutz
zero = Sundayhttp://perldoc.perl.org/functions/localtime.html
heeen
my $wday = (localtime($epoch))[6]; # Replacement for the last line to just get the day of the week
R. Bemrose
+2  A: 

It's a little baroque, but I always liked Date::Manip.

I don't think an alternate methodology is what you need, though. More likely, you need to stop feeding Date::Calc invalid dates.

What values is it erroring on?

chaos
+1  A: 

You could use Date::Simple.

use Date::Simple (':all');
my $date = ymd($year, $month, $day);
my $dow = $date->day_of_week();
Peter Stuifzand
Of course, changing modules doesn't make the calendar any different if it's an invalid date. :)
brian d foy
he, it seems the question was changed while I was answering the question
Peter Stuifzand
+1  A: 

As an alternative to heeen's answer, you can use strftime:

use Posix qw(strftime);
my $wday = strftime('%w', sec, min, hour, mday, mon, year); # 0 = Sunday, 1 = Monday, etc...
my $day_name = strftime('%a', sec, min, hour, mday, mon, year); # Sun, Mon, etc...
my $day_name_long = strftime('%A', sec, min, hour, mday, mon, year); # Sunday, Monday, etc...
R. Bemrose
+4  A: 

The error message says you're passing Date::Calc an invalid date. Don't do that. You can use Date::Calc's check_date function to decide if the date is valid.

use Date::Calc qw(Add_Delta_Days check_date Day_of_Week Delta_Days);

$this_day = (check_date($lyear, $month, $day)
             ? Day_of_Week($lyear, $month, $day)
             : 'INVALID');

Correcting invalid dates is more complicated, because it depends on how you're getting invalid dates, and what you want to do about them. For example, if the day might be out of range, and you wanted to correct April 31 to May 1, you could use

($lyear, $month, $day) = Add_Delta_Days($lyear, $month, 1,  $day-1);

But that won't correct an invalid year or month.

cjm