Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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);

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?

You could use Date::Simple.

use Date::Simple (':all');
my $date = ymd($year, $month, $day);
my $dow = $date->day_of_week();

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...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top