home *** CD-ROM | disk | FTP | other *** search
/ Netrunner 2004 October / NETRUNNER0410.ISO / regular / ActivePerl-5.8.4.810-MSWin32-x86.msi / _c26d44f1765fe7a470ed052b68fd0df6 < prev    next >
Encoding:
Text File  |  2004-06-01  |  10.9 KB  |  390 lines

  1. package HTTP::Date;  # $Date: 2003/10/23 19:11:32 $
  2.  
  3. $VERSION = sprintf("%d.%02d", q$Revision: 1.46 $ =~ /(\d+)\.(\d+)/);
  4.  
  5. require 5.004;
  6. require Exporter;
  7. @ISA = qw(Exporter);
  8. @EXPORT = qw(time2str str2time);
  9. @EXPORT_OK = qw(parse_date time2iso time2isoz);
  10.  
  11. use strict;
  12. require Time::Local;
  13.  
  14. use vars qw(@DoW @MoY %MoY);
  15. @DoW = qw(Sun Mon Tue Wed Thu Fri Sat);
  16. @MoY = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
  17. @MoY{@MoY} = (1..12);
  18.  
  19. my %GMT_ZONE = (GMT => 1, UTC => 1, UT => 1, Z => 1);
  20.  
  21.  
  22. sub time2str (;$)
  23. {
  24.     my $time = shift;
  25.     $time = time unless defined $time;
  26.     my ($sec, $min, $hour, $mday, $mon, $year, $wday) = gmtime($time);
  27.     sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT",
  28.         $DoW[$wday],
  29.         $mday, $MoY[$mon], $year+1900,
  30.         $hour, $min, $sec);
  31. }
  32.  
  33.  
  34. sub str2time ($;$)
  35. {
  36.     my $str = shift;
  37.     return undef unless defined $str;
  38.  
  39.     # fast exit for strictly conforming string
  40.     if ($str =~ /^[SMTWF][a-z][a-z], (\d\d) ([JFMAJSOND][a-z][a-z]) (\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$/) {
  41.     return eval {
  42.         my $t = Time::Local::timegm($6, $5, $4, $1, $MoY{$2}-1, $3-1900);
  43.         $t < 0 ? undef : $t;
  44.     };
  45.     }
  46.  
  47.     my @d = parse_date($str);
  48.     return undef unless @d;
  49.     $d[0] -= 1900;  # year
  50.     $d[1]--;        # month
  51.  
  52.     my $tz = pop(@d);
  53.     unless (defined $tz) {
  54.     unless (defined($tz = shift)) {
  55.         return eval { my $frac = $d[-1]; $frac -= ($d[-1] = int($frac));
  56.               my $t = Time::Local::timelocal(reverse @d) + $frac;
  57.               $t < 0 ? undef : $t;
  58.                 };
  59.     }
  60.     }
  61.  
  62.     my $offset = 0;
  63.     if ($GMT_ZONE{uc $tz}) {
  64.     # offset already zero
  65.     }
  66.     elsif ($tz =~ /^([-+])?(\d\d?):?(\d\d)?$/) {
  67.     $offset = 3600 * $2;
  68.     $offset += 60 * $3 if $3;
  69.     $offset *= -1 if $1 && $1 eq '-';
  70.     }
  71.     else {
  72.     eval { require Time::Zone } || return undef;
  73.     $offset = Time::Zone::tz_offset($tz);
  74.     return undef unless defined $offset;
  75.     }
  76.  
  77.     return eval { my $frac = $d[-1]; $frac -= ($d[-1] = int($frac));
  78.           my $t = Time::Local::timegm(reverse @d) + $frac;
  79.           $t < 0 ? undef : $t - $offset;
  80.         };
  81. }
  82.  
  83.  
  84. sub parse_date ($)
  85. {
  86.     local($_) = shift;
  87.     return unless defined;
  88.  
  89.     # More lax parsing below
  90.     s/^\s+//;  # kill leading space
  91.     s/^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*,?\s*//i; # Useless weekday
  92.  
  93.     my($day, $mon, $yr, $hr, $min, $sec, $tz, $ampm);
  94.  
  95.     # Then we are able to check for most of the formats with this regexp
  96.     (($day,$mon,$yr,$hr,$min,$sec,$tz) =
  97.         /^
  98.      (\d\d?)               # day
  99.         (?:\s+|[-\/])
  100.      (\w+)                 # month
  101.         (?:\s+|[-\/])
  102.      (\d+)                 # year
  103.      (?:
  104.            (?:\s+|:)       # separator before clock
  105.         (\d\d?):(\d\d)     # hour:min
  106.         (?::(\d\d))?       # optional seconds
  107.      )?                    # optional clock
  108.         \s*
  109.      ([-+]?\d{2,4}|(?![APap][Mm]\b)[A-Za-z]+)? # timezone
  110.         \s*
  111.      (?:\(\w+\))?           # ASCII representation of timezone in parens.
  112.         \s*$
  113.     /x)
  114.  
  115.     ||
  116.  
  117.     # Try the ctime and asctime format
  118.     (($mon, $day, $hr, $min, $sec, $tz, $yr) =
  119.     /^
  120.      (\w{1,3})             # month
  121.         \s+
  122.      (\d\d?)               # day
  123.         \s+
  124.      (\d\d?):(\d\d)        # hour:min
  125.      (?::(\d\d))?          # optional seconds
  126.         \s+
  127.      (?:([A-Za-z]+)\s+)?   # optional timezone
  128.      (\d+)                 # year
  129.         \s*$               # allow trailing whitespace
  130.     /x)
  131.  
  132.     ||
  133.  
  134.     # Then the Unix 'ls -l' date format
  135.     (($mon, $day, $yr, $hr, $min, $sec) =
  136.     /^
  137.      (\w{3})               # month
  138.         \s+
  139.      (\d\d?)               # day
  140.         \s+
  141.      (?:
  142.         (\d\d\d\d) |       # year
  143.         (\d{1,2}):(\d{2})  # hour:min
  144.             (?::(\d\d))?       # optional seconds
  145.      )
  146.      \s*$
  147.        /x)
  148.  
  149.     ||
  150.  
  151.     # ISO 8601 format '1996-02-29 12:00:00 -0100' and variants
  152.     (($yr, $mon, $day, $hr, $min, $sec, $tz) =
  153.     /^
  154.       (\d{4})              # year
  155.          [-\/]?
  156.       (\d\d?)              # numerical month
  157.          [-\/]?
  158.       (\d\d?)              # day
  159.      (?:
  160.            (?:\s+|[-:Tt])  # separator before clock
  161.         (\d\d?):?(\d\d)    # hour:min
  162.         (?::?(\d\d(?:\.\d*)?))?  # optional seconds (and fractional)
  163.      )?                    # optional clock
  164.         \s*
  165.      ([-+]?\d\d?:?(:?\d\d)?
  166.       |Z|z)?               # timezone  (Z is "zero meridian", i.e. GMT)
  167.         \s*$
  168.     /x)
  169.  
  170.     ||
  171.  
  172.     # Windows 'dir' 11-12-96  03:52PM
  173.     (($mon, $day, $yr, $hr, $min, $ampm) =
  174.         /^
  175.           (\d{2})                # numerical month
  176.              -
  177.           (\d{2})                # day
  178.              -
  179.           (\d{2})                # year
  180.              \s+
  181.           (\d\d?):(\d\d)([APap][Mm])  # hour:min AM or PM
  182.              \s*$
  183.         /x)
  184.  
  185.     ||
  186.     return;  # unrecognized format
  187.  
  188.     # Translate month name to number
  189.     $mon = $MoY{$mon} ||
  190.            $MoY{"\u\L$mon"} ||
  191.        ($mon =~ /^\d\d?$/ && $mon >= 1 && $mon <= 12 && int($mon)) ||
  192.            return;
  193.  
  194.     # If the year is missing, we assume first date before the current,
  195.     # because of the formats we support such dates are mostly present
  196.     # on "ls -l" listings.
  197.     unless (defined $yr) {
  198.     my $cur_mon;
  199.     ($cur_mon, $yr) = (localtime)[4, 5];
  200.     $yr += 1900;
  201.     $cur_mon++;
  202.     $yr-- if $mon > $cur_mon;
  203.     }
  204.     elsif (length($yr) < 3) {
  205.     # Find "obvious" year
  206.     my $cur_yr = (localtime)[5] + 1900;
  207.     my $m = $cur_yr % 100;
  208.     my $tmp = $yr;
  209.     $yr += $cur_yr - $m;
  210.     $m -= $tmp;
  211.     $yr += ($m > 0) ? 100 : -100
  212.         if abs($m) > 50;
  213.     }
  214.  
  215.     # Make sure clock elements are defined
  216.     $hr  = 0 unless defined($hr);
  217.     $min = 0 unless defined($min);
  218.     $sec = 0 unless defined($sec);
  219.  
  220.     # Compensate for AM/PM
  221.     if ($ampm) {
  222.     $ampm = uc $ampm;
  223.     $hr = 0 if $hr == 12 && $ampm eq 'AM';
  224.     $hr += 12 if $ampm eq 'PM' && $hr != 12;
  225.     }
  226.  
  227.     return($yr, $mon, $day, $hr, $min, $sec, $tz)
  228.     if wantarray;
  229.  
  230.     if (defined $tz) {
  231.     $tz = "Z" if $tz =~ /^(GMT|UTC?|[-+]?0+)$/;
  232.     }
  233.     else {
  234.     $tz = "";
  235.     }
  236.     return sprintf("%04d-%02d-%02d %02d:%02d:%02d%s",
  237.            $yr, $mon, $day, $hr, $min, $sec, $tz);
  238. }
  239.  
  240.  
  241. sub time2iso (;$)
  242. {
  243.     my $time = shift;
  244.     $time = time unless defined $time;
  245.     my($sec,$min,$hour,$mday,$mon,$year) = localtime($time);
  246.     sprintf("%04d-%02d-%02d %02d:%02d:%02d",
  247.         $year+1900, $mon+1, $mday, $hour, $min, $sec);
  248. }
  249.  
  250.  
  251. sub time2isoz (;$)
  252. {
  253.     my $time = shift;
  254.     $time = time unless defined $time;
  255.     my($sec,$min,$hour,$mday,$mon,$year) = gmtime($time);
  256.     sprintf("%04d-%02d-%02d %02d:%02d:%02dZ",
  257.             $year+1900, $mon+1, $mday, $hour, $min, $sec);
  258. }
  259.  
  260. 1;
  261.  
  262.  
  263. __END__
  264.  
  265. =head1 NAME
  266.  
  267. HTTP::Date - date conversion routines
  268.  
  269. =head1 SYNOPSIS
  270.  
  271.  use HTTP::Date;
  272.  
  273.  $string = time2str($time);    # Format as GMT ASCII time
  274.  $time = str2time($string);    # convert ASCII date to machine time
  275.  
  276. =head1 DESCRIPTION
  277.  
  278. This module provides functions that deal the date formats used by the
  279. HTTP protocol (and then some more).  Only the first two functions,
  280. time2str() and str2time(), are exported by default.
  281.  
  282. =over 4
  283.  
  284. =item time2str( [$time] )
  285.  
  286. The time2str() function converts a machine time (seconds since epoch)
  287. to a string.  If the function is called without an argument, it will
  288. use the current time.
  289.  
  290. The string returned is in the format preferred for the HTTP protocol.
  291. This is a fixed length subset of the format defined by RFC 1123,
  292. represented in Universal Time (GMT).  An example of a time stamp
  293. in this format is:
  294.  
  295.    Sun, 06 Nov 1994 08:49:37 GMT
  296.  
  297. =item str2time( $str [, $zone] )
  298.  
  299. The str2time() function converts a string to machine time.  It returns
  300. C<undef> if the format of $str is unrecognized, or the time is outside
  301. the representable range.  The time formats recognized are the same as
  302. for parse_date().
  303.  
  304. The function also takes an optional second argument that specifies the
  305. default time zone to use when converting the date.  This parameter is
  306. ignored if the zone is found in the date string itself.  If this
  307. parameter is missing, and the date string format does not contain any
  308. zone specification, then the local time zone is assumed.
  309.  
  310. If the zone is not "C<GMT>" or numerical (like "C<-0800>" or
  311. "C<+0100>"), then the C<Time::Zone> module must be installed in order
  312. to get the date recognized.
  313.  
  314. =item parse_date( $str )
  315.  
  316. This function will try to parse a date string, and then return it as a
  317. list of numerical values followed by a (possible undefined) time zone
  318. specifier; ($year, $month, $day, $hour, $min, $sec, $tz).  The $year
  319. returned will B<not> have the number 1900 subtracted from it and the
  320. $month numbers start with 1.
  321.  
  322. In scalar context the numbers are interpolated in a string of the
  323. "YYYY-MM-DD hh:mm:ss TZ"-format and returned.
  324.  
  325. If the date is unrecognized, then the empty list is returned.
  326.  
  327. The function is able to parse the following formats:
  328.  
  329.  "Wed, 09 Feb 1994 22:23:32 GMT"       -- HTTP format
  330.  "Thu Feb  3 17:03:55 GMT 1994"        -- ctime(3) format
  331.  "Thu Feb  3 00:00:00 1994",           -- ANSI C asctime() format
  332.  "Tuesday, 08-Feb-94 14:15:29 GMT"     -- old rfc850 HTTP format
  333.  "Tuesday, 08-Feb-1994 14:15:29 GMT"   -- broken rfc850 HTTP format
  334.  
  335.  "03/Feb/1994:17:03:55 -0700"   -- common logfile format
  336.  "09 Feb 1994 22:23:32 GMT"     -- HTTP format (no weekday)
  337.  "08-Feb-94 14:15:29 GMT"       -- rfc850 format (no weekday)
  338.  "08-Feb-1994 14:15:29 GMT"     -- broken rfc850 format (no weekday)
  339.  
  340.  "1994-02-03 14:15:29 -0100"    -- ISO 8601 format
  341.  "1994-02-03 14:15:29"          -- zone is optional
  342.  "1994-02-03"                   -- only date
  343.  "1994-02-03T14:15:29"          -- Use T as separator
  344.  "19940203T141529Z"             -- ISO 8601 compact format
  345.  "19940203"                     -- only date
  346.  
  347.  "08-Feb-94"         -- old rfc850 HTTP format    (no weekday, no time)
  348.  "08-Feb-1994"       -- broken rfc850 HTTP format (no weekday, no time)
  349.  "09 Feb 1994"       -- proposed new HTTP format  (no weekday, no time)
  350.  "03/Feb/1994"       -- common logfile format     (no time, no offset)
  351.  
  352.  "Feb  3  1994"      -- Unix 'ls -l' format
  353.  "Feb  3 17:03"      -- Unix 'ls -l' format
  354.  
  355.  "11-15-96  03:52PM" -- Windows 'dir' format
  356.  
  357. The parser ignores leading and trailing whitespace.  It also allow the
  358. seconds to be missing and the month to be numerical in most formats.
  359.  
  360. If the year is missing, then we assume that the date is the first
  361. matching date I<before> current month.  If the year is given with only
  362. 2 digits, then parse_date() will select the century that makes the
  363. year closest to the current date.
  364.  
  365. =item time2iso( [$time] )
  366.  
  367. Same as time2str(), but returns a "YYYY-MM-DD hh:mm:ss"-formatted
  368. string representing time in the local time zone.
  369.  
  370. =item time2isoz( [$time] )
  371.  
  372. Same as time2str(), but returns a "YYYY-MM-DD hh:mm:ssZ"-formatted
  373. string representing Universal Time.
  374.  
  375.  
  376. =back
  377.  
  378. =head1 SEE ALSO
  379.  
  380. L<perlfunc/time>, L<Time::Zone>
  381.  
  382. =head1 COPYRIGHT
  383.  
  384. Copyright 1995-1999, Gisle Aas
  385.  
  386. This library is free software; you can redistribute it and/or
  387. modify it under the same terms as Perl itself.
  388.  
  389. =cut
  390.