home *** CD-ROM | disk | FTP | other *** search
/ Acorn User 10 / AU_CD10.iso / Updates / Perl / Perl_Libs / site_perl / HTTP / Date.pm < prev    next >
Text File  |  1997-12-02  |  9KB  |  331 lines

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