0

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?

brian d foy
  • 129,424
  • 31
  • 207
  • 592
CheeseConQueso
  • 5,831
  • 29
  • 93
  • 126
  • What exactly were your inputs? If you put in, for example, February 31st, it will throw this same error, and there is very little you can do about it except to sanitize the date first. – Jack M. Feb 20 '09 at 20:08

5 Answers5

4

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
  • 61,471
  • 9
  • 126
  • 175
2
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
  • 4,736
  • 2
  • 21
  • 24
2

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
  • 122,029
  • 33
  • 303
  • 309
1

You could use Date::Simple.

use Date::Simple (':all');
my $date = ymd($year, $month, $day);
my $dow = $date->day_of_week();
Peter Stuifzand
  • 5,084
  • 1
  • 23
  • 28
1

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...
Powerlord
  • 87,612
  • 17
  • 125
  • 175