您可以使用核心Time::Local模块,然后使用localtime
. 工作日 0 对应于星期日,6 对应于星期六。
#! /usr/bin/env perl
use strict;
use warnings;
use Time::Local;
my @dates = qw(
2012-05-01
2012-05-02
2012-05-03
2012-05-04
2012-05-05
2012-05-06
);
my @days = qw/ Sun Mon Tue Wed Thu Fri Sat /;
foreach my $date (@dates) {
my($yyyy,$mm,$dd) = split /-/, $date;
my $time_t = timelocal 0, 0, 0, $dd, $mm-1, $yyyy-1900;
my $wday = (localtime $time_t)[6];
my $weekend = ($wday == 0 || $wday == 6) ? " *" : "";
print "$date: $days[$wday] ($wday)$weekend\n";
}
输出:
2012-05-01:周二(2)
2012-05-02: 星期三 (3)
2012-05-03:周四(4)
2012-05-04:周五(5)
2012-05-05: 星期六 (6) *
2012-05-06: 太阳 (0) *
为了好玩,您可以使用 Swiss Army Chainsaw 并抓取cal实用程序的输出。
#! /usr/bin/env perl
use strict;
use warnings;
use 5.10.0; # for smart matching
sub weekday_type {
my($date) = @_;
die "$0: unexpected date '$date'"
unless my($yyyy,$mm,$dd) =
$date =~ /^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})$/;
my $calendar = `cal -m $mm $yyyy`;
die "$0: cal -m $mm $yyyy failed" if $?;
for (split /\n/, $calendar) {
if (/^ \s* [0-9]{1,2} (?: \s+ [0-9]{1,2})* \s*$/x) {
my @dates = split;
my @weekend = splice @dates, @dates > 1 ? -2 : -1;
return "weekend" if ($dd+0) ~~ @weekend;
}
}
"weekday";
}
像这样使用它
my @dates = qw(
2012-05-01
2012-05-02
2012-05-03
2012-05-04
2012-05-05
2012-05-06
);
my @days = qw/ Sun Mon Tue Wed Thu Fri Sat /;
foreach my $date (@dates) {
my $type = weekday_type $date;
print "$date: $type\n";
}
输出:
2012-05-01:平日
2012-05-02:工作日
2012-05-03:平日
2012-05-04:平日
2012-05-05:周末
2012-05-06:周末
我不建议在生产中这样做。