home *** CD-ROM | disk | FTP | other *** search
/ CLIX - Fazer Clix Custa Nix / CLIX-CD.cdr / mac / lib / HTTP / Date.pm < prev    next >
Text File  |  1997-09-05  |  9KB  |  325 lines

  1. # $Id: Date.pm,v 1.26 1997/09/01 08:39:23 aas Exp $
  2. #
  3. package HTTP::Date;
  4.  
  5. =head1 NAME
  6.  
  7. time2str, str2time - date conversion routines
  8.  
  9. =head1 SYNOPSIS
  10.  
  11.  use HTTP::Date;
  12.  
  13.  $stringGMT = time2str(time);   # Format as GMT ASCII time
  14.  $time = str2time($stringGMT);  # convert ASCII date to machine time
  15.  
  16. =head1 DESCRIPTION
  17.  
  18. This module provides two functions that deal with the HTTP date format.
  19.  
  20. =head2 time2str([$time])
  21.  
  22. The time2str() function converts a machine time (seconds since epoch)
  23. to a string.  If the function is called without an argument, it will
  24. use the current time.
  25.  
  26. The string returned is in the format defined by the HTTP/1.0
  27. specification.  This is a fixed length subset of the format defined by
  28. RFC 1123, represented in Universal Time (GMT).  An example of this
  29. format is:
  30.  
  31.    Thu, 03 Feb 1994 17:09:00 GMT
  32.  
  33. =head2 str2time($str [, $zone])
  34.  
  35. The str2time() function converts a string to machine time.  It returns
  36. C<undef> if the format is unrecognized, or the year is not between 1970
  37. and 2038.  The function is able to parse the following formats:
  38.  
  39.  "Wed, 09 Feb 1994 22:23:32 GMT"       -- HTTP format
  40.  "Thu Feb  3 17:03:55 GMT 1994"        -- ctime(3) format
  41.  "Thu Feb  3 00:00:00 1994",           -- ANSI C asctime() format
  42.  "Tuesday, 08-Feb-94 14:15:29 GMT"     -- old rfc850 HTTP format
  43.  "Tuesday, 08-Feb-1994 14:15:29 GMT"   -- broken rfc850 HTTP format
  44.  
  45.  "03/Feb/1994:17:03:55 -0700"   -- common logfile format
  46.  "09 Feb 1994 22:23:32 GMT"     -- HTTP format (no weekday)
  47.  "08-Feb-94 14:15:29 GMT"       -- rfc850 format (no weekday)
  48.  "08-Feb-1994 14:15:29 GMT"     -- broken rfc850 format (no weekday)
  49.  
  50.  "1994-02-03 14:15:29 -0100"    -- ISO 8601 format
  51.  "1994-02-03 14:15:29"          -- zone is optional
  52.  "1994-02-03"                   -- only date
  53.  "1994-02-03T14:15:29"          -- Use T as separator
  54.  "19940203T141529Z"             -- ISO 8601 compact format
  55.  "19940203"                     -- only date
  56.  
  57.  "08-Feb-94"         -- old rfc850 HTTP format    (no weekday, no time)
  58.  "08-Feb-1994"       -- broken rfc850 HTTP format (no weekday, no time)
  59.  "09 Feb 1994"       -- proposed new HTTP format  (no weekday, no time)
  60.  "03/Feb/1994"       -- common logfile format     (no time, no offset)
  61.  
  62.  "Feb  3  1994"      -- Unix 'ls -l' format
  63.  "Feb  3 17:03"      -- Unix 'ls -l' format
  64.  
  65.  "11-15-96  03:52PM" -- Windows 'dir' format
  66.  
  67. The parser ignores leading and trailing whitespace.  It also allow the
  68. seconds to be missing and the month to be numerical in most formats.
  69.  
  70. The str2time() function takes an optional second argument that
  71. specifies the default time zone to use when converting the date.  This
  72. zone specification should be numerical (like "-0800" or "+0100") or
  73. "GMT".  This parameter is ignored if the zone is specified in the date
  74. string itself.  It this parameter is missing, and the date string
  75. format does not contain any zone specification then the local time
  76. zone is assumed.
  77.  
  78. If the year is missing, then we assume that the date is the first
  79. matching date I<before> current time.
  80.  
  81. =head1 BUGS
  82.  
  83. Non-numerical time zones (like MET, PST) are all treated like GMT.
  84. Do not use them.  HTTP does not use them.
  85.  
  86. The str2time() function has been told how to parse far too many
  87. formats.  This makes the module name misleading. To be sure it is
  88. really misleading you can also import the time2iso() and time2isoz()
  89. functions.  They work like time2str() but produce ISO-8601 formated
  90. strings (YYYY-MM-DD hh:mm:ss).
  91.  
  92. =head1 COPYRIGHT
  93.  
  94. Copyright 1995-1997, Gisle Aas
  95.  
  96. This library is free software; you can redistribute it and/or
  97. modify it under the same terms as Perl itself.
  98.  
  99. =cut
  100.  
  101.  
  102. $VERSION = sprintf("%d.%02d", q$Revision: 1.26 $ =~ /(\d+)\.(\d+)/);
  103. sub Version { $VERSION; }
  104.  
  105. require 5.002;
  106. require Exporter;
  107. @ISA = qw(Exporter);
  108. @EXPORT = qw(time2str str2time);
  109. @EXPORT_OK = qw(time2iso time2isoz);
  110.  
  111. use Time::Local ();
  112.  
  113. use strict;
  114. use vars qw(@DoW @MoY %MoY);
  115.  
  116. #@DoW = qw(Sunday Monday Tuesday Wednesday Thursday Friday Saturday);
  117. @DoW = qw(Sun Mon Tue Wed Thu Fri Sat);
  118. @MoY = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
  119. # Build %MoY hash
  120. my $i = 0;
  121. foreach(@MoY) {
  122.    $MoY{lc $_} = $i++;
  123. }
  124.  
  125. my($current_month, $current_year) = (localtime)[4, 5];
  126.  
  127.  
  128.  
  129.  
  130. sub time2str (;$)
  131. {
  132.    my $time = shift;
  133.    $time = time unless defined $time;
  134.    my ($sec, $min, $hour, $mday, $mon, $year, $wday) = gmtime($time);
  135.    sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT",
  136.        $DoW[$wday],
  137.        $mday, $MoY[$mon], $year+1900,
  138.        $hour, $min, $sec);
  139. }
  140.  
  141.  
  142.  
  143. sub str2time ($;$)
  144. {
  145.    local($_) = shift;
  146.    return undef unless defined;
  147.    my($default_zone) = @_;
  148.  
  149.    # Remove useless weekday, if it exists
  150.    s/^\s*(?:sun|mon|tue|wed|thu|fri|sat)\w*,?\s*//i;
  151.  
  152.    my($day, $mon, $yr, $hr, $min, $sec, $tz, $aorp);
  153.    my $offset = 0;  # used when compensating for timezone
  154.  
  155.  PARSEDATE: {
  156.       # Then we are able to check for most of the formats with this regexp
  157.       ($day,$mon,$yr,$hr,$min,$sec,$tz) =
  158.     /^\s*
  159.      (\d\d?)               # day
  160.         (?:\s+|[-\/])
  161.      (\w+)                 # month
  162.         (?:\s+|[-\/])
  163.      (\d+)                 # year
  164.      (?:
  165.            (?:\s+|:)       # separator before clock
  166.         (\d\d?):(\d\d)     # hour:min
  167.         (?::(\d\d))?       # optional seconds
  168.      )?                    # optional clock
  169.         \s*
  170.      ([-+]?\d{2,4}|GMT|gmt)? # timezone
  171.         \s*$
  172.     /x
  173.       and last PARSEDATE;
  174.  
  175.       # Try the ctime and asctime format
  176.       ($mon, $day, $hr, $min, $sec, $tz, $yr) =
  177.     /^\s*                  # allow intial whitespace
  178.      (\w{1,3})             # month
  179.         \s+
  180.      (\d\d?)               # day
  181.         \s+
  182.      (\d\d?):(\d\d)        # hour:min
  183.      (?::(\d\d))?          # optional seconds
  184.         \s+
  185.      (?:(GMT|gmt)\s+)?     # optional GMT timezone
  186.      (\d+)                 # year
  187.         \s*$               # allow trailing whitespace
  188.     /x
  189.       and last PARSEDATE;
  190.  
  191.       # Then the Unix 'ls -l' date format
  192.       ($mon, $day, $yr, $hr, $min) =
  193.     /^\s*
  194.      (\w{3})               # month
  195.         \s+
  196.      (\d\d?)               # day
  197.         \s+
  198.      (?:
  199.         (\d\d\d\d) |       # year
  200.         (\d{1,2}):(\d{2})  # hour:min
  201.      )
  202.      \s*$
  203.        /x
  204.      and last PARSEDATE;
  205.  
  206.       # ISO 8601 format '1996-02-29 12:00:00 -0100' and variants
  207.       ($yr, $mon, $day, $hr, $min, $sec, $tz) =
  208.     /^\s*
  209.       (\d{4})              # year
  210.          [-\/]?
  211.       (\d\d?)              # numerical month
  212.          [-\/]?
  213.       (\d\d?)              # day
  214.      (?:
  215.            (?:\s+|:|T|-)   # separator before clock
  216.         (\d\d?):?(\d\d)    # hour:min
  217.         (?::?(\d\d))?      # optional seconds
  218.      )?                    # optional clock
  219.         \s*
  220.      ([-+]?\d\d?:?(:?\d\d)?
  221.       |Z|z)?               # timezone  (Z is "zero meridian", i.e. GMT)
  222.         \s*$
  223.     /x
  224.       and last PARSEDATE;
  225.  
  226.       # Windows 'dir' 11-12-96  03:52PM
  227.       ($mon, $day, $yr, $hr, $min, $aorp) =
  228.         /^\s*
  229.           (\d{2})                # numerical month
  230.              -
  231.           (\d{2})                # day
  232.              -
  233.           (\d{2})                # year
  234.              \s+
  235.           (\d\d?):(\d\d)([apAP][mM])  # hour:min AM or PM
  236.              \s*$
  237.         /x
  238.           and last PARSEDATE;
  239.  
  240.       # If it is not recognized by now we give up
  241.       return undef;
  242.    }
  243.  
  244.    # Translate month name to number
  245.    if ($mon =~ /^\d+$/) {
  246.      # numeric month
  247.      return undef if $mon < 1 || $mon > 12;
  248.      $mon--;
  249.    } else {
  250.      $mon = lc $mon;
  251.      return undef unless exists $MoY{$mon};
  252.      $mon = $MoY{$mon};
  253.    }
  254.  
  255.    # If the year is missing, we assume some date before the current,
  256.    # because these date are mostly present on "ls -l" listings.
  257.    unless (defined $yr) {
  258.     $yr = $current_year;
  259.     $yr-- if $mon > $current_month;
  260.     }
  261.  
  262.    # Then we check if the year is acceptable
  263.    return undef if $yr > 99 && $yr < 1900;  # We ignore these years
  264.    $yr += 100 if $yr < 50;  # a stupid thing to do???
  265.    $yr -= 1900 if $yr >= 1900;
  266.    # The $yr is now relative to 1900 (as expected by timelocal())
  267.  
  268.    # timelocal() seems to go into an infinite loop if it is given out
  269.    # of range parameters.  Let's check the year at least.
  270.  
  271.    # Epoch counter maxes out in year 2038, assuming "time_t" is 32 bit
  272.    return undef if $yr > 138;
  273.    return undef if $yr <  70;  # 1970 is Unix epoch
  274.  
  275.    # Compensate for AM/PM
  276.    if ($aorp) {
  277.        $aorp = uc $aorp;
  278.        $hr = 0 if $hr == 12 && $aorp eq 'AM';
  279.        $hr += 12 if $aorp eq 'PM' && $hr != 12;
  280.    }
  281.  
  282.    # Make sure things are defined
  283.    for ($sec, $min, $hr) {  $_ = 0 unless defined   }
  284.  
  285.    # Should we compensate for the timezone?
  286.    $tz = $default_zone unless defined $tz;
  287.    return Time::Local::timelocal($sec, $min, $hr, $day, $mon, $yr)
  288.      unless defined $tz;
  289.  
  290.    # We can calculate offset for numerical time zones
  291.    if ($tz =~ /^([-+])?(\d\d?):?(\d\d)?$/) {
  292.        $offset = 3600 * $2;
  293.        $offset += 60 * $3 if $3;
  294.        $offset *= -1 if $1 && $1 ne '-';
  295.    }
  296.    Time::Local::timegm($sec, $min, $hr, $day, $mon, $yr) + $offset;
  297. }
  298.  
  299.  
  300.  
  301. # And then some bloat because I happen to like the ISO 8601 time
  302. # format.
  303.  
  304. sub time2iso (;$)
  305. {
  306.    my $time = shift;
  307.    $time = time unless defined $time;
  308.    my($sec,$min,$hour,$mday,$mon,$year) = localtime($time);
  309.    sprintf("%04d-%02d-%02d %02d:%02d:%02d",
  310.        $year+1900, $mon+1, $mday, $hour, $min, $sec);
  311. }
  312.  
  313.  
  314. sub time2isoz (;$)
  315. {
  316.     my $time = shift;
  317.     $time = time unless defined $time;
  318.     my($sec,$min,$hour,$mday,$mon,$year) = gmtime($time);
  319.     sprintf("%04d-%02d-%02d %02d:%02d:%02dZ",
  320.             $year+1900, $mon+1, $mday, $hour, $min, $sec);
  321. }
  322.  
  323. 1;
  324.  
  325.