Eric J. Roode on Wed, 16 Jul 2003 18:39:08 -0400


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: Which Dave Rolsky talk do you want to hear?


On Wed, Jul 16, 2003 at 12:22:05AM -0400, Walt Mankowski wrote:
...
> > - Dates & Times in Perl (c 1.5hrs)

Hey, this reminds me of something I've been meaning to announce here....

I have written a new module, now available on CPAN, called Time::Format.
It is meant to make time and date formatting simple and easy.

The "standard" way of formatting dates and times is to use strftime, in
the POSIX module.  There are two glaring problems with strftime.  One,
its formatting codes are cryptic and difficult to remember.  For example,
I can never remember that %A is the weekday name spelled out, %B is the 
month name spelled out, %e is the two-character day of the month, etc.
These are archaic holdovers from the dark days of C.  The other problem
is that the supposedly standard strftime actually varies quite a lot
from platform to platform.

The other standard way of formatting times and dates is rolling your
own, by calling localtime in list context and manually piecing together
the returned values.  A quick show of hands -- how many of you are
tired of writing "$t[4]++; $t[5]+=1900;"?    ;-)

Time::Format's formatting codes are meant to be easy to remember.  Here
are a sample:

    yyyy  - four-digit year
    yy    - two-digit year
    hh    - hour, 00-23
    ss    - second
    Month - full month name, spelled out
    Mon   - three-letter month name abbreviation

The format string that duplicates the functionality of localtime is:
    'Day Mon ?d hh:mm:ss yyyy'

A simple timestamp would be formatted as:
    'yyyy/mm/dd hh:mm:ss.mmm'

(where "mmm" is milliseconds).

Most of the format codes take up exactly as many characters as their
output will take.  The exceptions are the variable-width output, for
example full month names.

The primary interface to the time formatting function is a tied hash,
%time.  This makes it easy to interpolate dates and times into strings,
which is where you generally use them:

 print "File last modified on $time{'yyyy/mm/dd',$^T - 86400*-M $file}";

(As many of you know, perl evaluates arbitrary expressions within the
curly braces of a hash, even if the hash is being interpolated into a
string).

Time::Format has many other features, such as an interface to the
Date::Manip module's handy UnixDate function, and an interface to the
dreaded POSIX::strftime.  It also handles international locales (month
and weekday names and abbreviations are displayed in the language
appropriate for the current locale).

Check it out, and let me know what you think.  Thanks.
-- 
Eric J. Roode                                            sdn@comcast.net
$_ = reverse sort $/.r , qw p ekca ts lre reh
uJ p, map $_ . $" , qw e p h tona e and print

Attachment: pgpMJlfUqLMoh.pgp
Description: PGP signature