Howto get the first day of the week by week number
nite_man
created: 2006-05-23 17:05:35
Today I faced with small problem. I prepared a chart where data was split by weeks. It was very easy except one thing: display the first day of the week instead of week number. Here is a one way to do it (the main idea belongs to my co-worker Igor) P. S. Other way is to use Date::Calc - ($y, $m, $d) = Monday_of_Week($week, $year);
sub get_date_by_week {
    my $week = shift || 1;
    my $year = shift || (localtime)[5];
    my $pattern = shift || '%d/%m';
    my $t = timelocal(0, 0, 0, 1, 0, $year);
    my $w = (localtime($t))[6];
    $w = ($w - 2) % 7 + 1;
    my $wc = $week * 7 - $w;
    return strftime($pattern, localtime($t + $wc * 24 * 3600));
}
Re: Howto get the first day of the week by week number
created: 2006-05-23 17:41:44
Not all days are of the same length in all time zones, so $wc * 24 * 3600 is wrong. The simplest workaround is to use a time zone that doesn't have daylight savings time to do date calculations. For example, the following doesn't have that bug:
sub get_date_by_week {
    my $week = shift || 1;
    my $year = shift || (localtime)[5];
    my $pattern = shift || '%d/%m';
    my $t = timegm(0, 0, 0, 1, 0, $year);
    my $w = (gmtime($t))[6];
    $w = ($w - 2) % 7 + 1;
    my $wc = $week * 7 - $w;
    return strftime($pattern, gmtime($t + $wc * 24 * 3600));
}

perlmonks.org content © perlmonks.org and ikegami, nite_man

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03