http://qs321.pair.com?node_id=81347

MrCromeDome has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to split a date a couple of different ways. In one instance, I want only the date portion. In the other, I want the date and time, but not seconds, milliseconds, etc.

For example, my database gives me the following date, which I promptly assign to $doc_date:

2001-05-17 14:40:00.123
Using the following code, I can get only the date portion:
($date, $discard) = split(" ",$doc_date);
However, if I change my code to:
($date, $discard) = split(":",$doc_date);
I know that I will only get the hour, not the hour and minutes. How can I change my code to give me the proper time (in this case, 14:40), but not the seconds or milliseconds?

Thanks!

Replies are listed 'Best First'.
Re: Date parsing
by Albannach (Monsignor) on May 17, 2001 at 23:55 UTC
    Sometimes split is overkill:

    print substr('2001-05-17 14:40:00.123',11,5) gives you 14:40, and as this looks like a very fixed (stable) format, I see no reason not to rely on the column positions, though you may want to verify that.

    --
    I'd like to be able to assign to an luser

Re: Date parsing
by sutch (Curate) on May 17, 2001 at 23:51 UTC
(tye)Re: Date parsing
by tye (Sage) on May 17, 2001 at 23:54 UTC
    my $time= ( $doc_date =~ /\s(\d+:\d+):/ );         - tye (but my friends call me "Tye")
Re: Date parsing
by aijin (Monk) on May 17, 2001 at 23:52 UTC
    You could try splitting on non-numeric characters.

    my ($year,$month,$day,$hours,$minutes,$seconds,$milliseconds) = split( +"\D",$doc_date);
Re: Date parsing
by malloc (Pilgrim) on May 17, 2001 at 23:53 UTC
    why not: $date =~ s/(:.*):.*/$1/g; ?? -malloc
Re: Date parsing
by BigJoe (Curate) on May 18, 2001 at 01:05 UTC
    This is not a straight perl answer but most Databases have a builtin date formatting commands. In Oracle you have the command TO_CHAR()used like this:

    select colA, colB, to_char(date_column, 'Month DD, YYYY') from table;

    This will convert the date into the name of the month along with the numeric day and a 4 digit year. OR

    select colA, colB, to_char(date_column, 'HH24:MI:SS') from table;

    This one gives you the hours in military fallowed by a colon then minutes then a colon then seconds.



    --BigJoe

    Learn patience, you must.
    Young PerlMonk, craves Not these things.
    Use the source Luke.