in reply to Date::Format handling of ISO week number format

I'm not sure whether you want to parse these date formats, or produce them. Since you mention Date::Format, I assume you want to format them. In which case, what's wrong with the following?

use strict; use Date::Format 'time2str'; print time2str("%Y-W%W", time);

If you want to zero-fill the week numbers, you have to use the slightly more cumbersome:

my $t = time; print time2str("%Y-W", $t) . sprintf("%02d",time2str("%W", $t));

• another intruder with the mooring in the heart of the Perl

Replies are listed 'Best First'.
Re^2: Date::Format handling of ISO week number format
by Oberon (Monk) on Jan 15, 2008 at 20:06 UTC
    > what's wrong with the following?
    > :
    > print time2str("%Y-W%W", time);

    Because when the date falls in the first week of the year or the last week of the year, that'll be wrong about half the time. For instance,

    use strict; use warnings; use Date::Manip qw<UnixDate>; use Date::Parse qw<str2time>; use Date::Format qw<time2str>; print UnixDate("12/31/2007", "%L-W%W"), "\n"; # prints "200 +8-W01" print time2str("%Y-W%W", str2time("12/31/2007")), "\n"; # prints "200 +7-W52" (!!)
    Actually, I thought it would print "2007-W01" ... I guess D::F's %W is broken to go along with its lack of UnixDate-equivalent-%L. At least it works better than I thought, I suppose ... but of course, according to ISO 8601, 2007-W52 is still wrong.

      Ah, well that sucks. I would file a bug report. Since that doesn't work, I shall return to my first idea, which is to use Date::Calc. I didn't even know about Date::Format until you pointed it out.

      #! /usr/local/bin/perl -w use strict; use Date::Calc 'Week_of_Year'; my ($y, $m, $d) = split m{/}, shift || '2007/12/31'; my ($week,$year) = Week_of_Year($y, $m, $d); printf "%04d-W%02d\n", $year, $week;

      You might want to wrap that up in a little routine and be done with it. It will certainly be far faster than using Date::Manip

      • another intruder with the mooring in the heart of the Perl

        That's a good idea, grinder. It won't be quite as easy as just writing a routine, since I have to be able to handle any given format coming in, but I think I can hack something together. Just scan the format for either %L or %W and, if I see either one, call Week_of_Year and do the substitution myself. Then I can pass it off to time2str if there are any %'s left.

        Not super elegant, perhaps, but definitely workable. Thanx!