[僕] 指定日から一ヶ月後までに指定した曜日が何個あるか求める

僕ト云フ事

たろマークはてなブックマーク

2009年10月10日

[perl] 指定日から一ヶ月後までに指定した曜日が何個あるか求める

一ヶ月だとどの曜日も4回は必ずあるよね。29日以上ある月の場合に余った日の中に指定した曜日があれば ++ する。もっとスマートにかけるような気もする。そしてあってるのかどうかわからないw

use strict;
use warnings;
use utf8;
 
use Test::More qw/no_plan/;
use DateTime;
 
is count_wdays(7, 2009, 10, 10), 5;
is count_wdays(6, 2009, 10, 10), 5;
is count_wdays(6, 2009, 9, 13), 4;
is count_wdays(1, 2010, 1, 12), 4;
is count_wdays(3, 2010, 1, 12), 5;
is count_wdays(7, 2010, 2, 1), 4;
is count_wdays(3, 2010, 6, 11), 4;
 
sub count_wdays {
    my ( $wday, $year, $month, $day ) = @_;
 
    my $first = DateTime->new(year => $year, month => $month, day => $day);
    my $last = $first->clone->add( months => 1, end_of_month => 'limit' );
 
    # 指定日から一ヶ月後までの日数を求める
    my $dur = $last->delta_days($first);
    my $days = $dur->in_units('days');
 
    my $count = sprintf("%d", $days / 7);
    my $remainder = $days % 7;
 
    if ( $remainder ) {
        my $min = $last->subtract( days => $remainder )->wday;
        my $max = $min + $remainder;
        if ( $min <= $wday && $max >= $wday ) {
            $count++;
        }
    }
 
    return $count;
}

これで間違いなければ、たぶん引数増やして最終日指定できるようにしてもうまく計算できると思うんだけどどうだろ。

こういう CPAN モジュールありそうだけどわからなかった。

トラックバック

このエントリーのトラックバックURL:
http://vkgtaro.jp/cgi-bin/mt/mt-tb.cgi/666

コメントを投稿