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?

1
  • 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, 2009 at 20:08

5 Answers 5

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.

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);
3
  • I forget - is the day of the week based on 0 or 1? Feb 20, 2009 at 19:12
  • Based on 0. Use qw(Sunday Monday Tuesday Wednesday Thursday Friday Saturday) to translate $wday to the day of the week.
    – Chris Lutz
    Feb 20, 2009 at 19:17
  • my $wday = (localtime($epoch))[6]; # Replacement for the last line to just get the day of the week
    – Powerlord
    Feb 20, 2009 at 19:18
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?

1

You could use Date::Simple.

use Date::Simple (':all');
my $date = ymd($year, $month, $day);
my $dow = $date->day_of_week();
2
  • Of course, changing modules doesn't make the calendar any different if it's an invalid date. :) Feb 20, 2009 at 22:48
  • he, it seems the question was changed while I was answering the question Mar 12, 2009 at 21:35
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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.