20 December 2005
This post may be outdated due to it was written on 2005. The links may be broken. The code may be not working anymore. Leave comments if needed.
前几天看 use.perl 的时候看到 jonasbn 写了个 journal: Date::Holidays::* - coming to your country?.
觉得我也可以参加,就琢磨着写了个 Date::Holidays::CN

perldoc

目前应该可以在 CPAN 上找到。找不到的话可以访问 http://www.fayland.org/CPAN/
use Date::Holidays::CN;

my ($year, $month, $day) = (localtime)[ 5, 4, 3 ];
$year += 1900;
$month += 1;
if (my $holidayname = is_cn_holiday( $year, $month, $day )) {
print "这是个 $holidayname";
}

my $h = cn_holidays($year);
printf "10 月 1 日是 '%s'\n", $h->{'1001'};

上面这一段代码是为了符合 Date::Holidays 的 API 而写的。
# suggested
use Date::Holidays::CN qw/is_cn_solar_holiday is_cn_lunar_holiday/;
my $holidayname = is_cn_solar_holiday( 2005, 10, 1 ); # $day = '国庆节'
my $is_holiday = is_cn_lunar_holiday( 2005, 9, 18 ); # $day = '中秋节'
这一段我比较推荐。因为中国的特殊国情。:-)

瑕疵

目前 cn_holidays 里没有阴历的日子。打算下一版本加进去。
另外因为采用了 DateTime::Calendar::Chinese 所以这速度实在是有点不可忍受。不过我找不到另外的处理阴历的模块,只好忍忍了。

过程

在写的过程中碰到了很奇怪的问题。这问题我发到了 PerlChina/BBS 和 PerlChina/Maillist 上了。
后来用 from_object 代替了 from_epoch, 没想到就搞定了。
my $dt2 = DateTime->new(
   year => $year,
   month => $month,
   day => $day,
   hour => 0,
   minute => 0,
   second => 0,
   nanosecond => 500000000,
   time_zone => 'Asia/Shanghai',
);
# ouch! the DateTime::Calendar::Chinese is a bit too slow!
my $dt = DateTime::Calendar::Chinese->from_object(object => $dt2);
return $LUNAR->{sprintf "%02d%02d", $dt->month, $dt->day};
如果诸位以后有机会用到这 DateTime::Calendar::Chinese 模块的话,小心用 from_object 可能比较好。

Enjoy!

如果有任何问题,可以联系我。比如说要增加某一节日。:->
my mail: fayland at gmail.com


blog comments powered by Disqus