Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: How to format timestamps M/D/Y h:mm:ss AMPM (e.g., 4/8/2013 6:09:03 PM)?

by Jim (Curate)
on May 14, 2013 at 04:07 UTC ( #1033397=note: print w/ replies, xml ) Need Help??


in reply to How to format timestamps M/D/Y h:mm:ss AMPM (e.g., 4/8/2013 6:09:03 PM)?

(I'm replying to my own post because I believe I've found the best general solution to my problem.)

Once I'd figured out that I could use DateTime::format_cldr() to render the timestamps in the required format, it seemed incongruous to be parsing them using DateTime::Format::Strptime. The new carpet made me realize I needed to replace the drapes. I was doing this…

        pattern => '%Y%m%d %H:%M:%S',

…and this…

    my $pattern = 'M/d/y h:mm:ss a';

…in two successive statements, which is inelegant. So I decided to use CLDR to parse the timestamps as well as to format them. Doing this neatens and tightens the code.

#!perl use v5.14; use strict; use warnings; use DateTime; use DateTime::Format::CLDR; my $parser = DateTime::Format::CLDR->new( pattern => 'yyyyMMdd HH:mm:ss', on_error => 'croak', ); my $format = 'M/d/y h:mm:ss a'; while (my $timestamp = <DATA>) { chomp $timestamp; $timestamp = $parser->parse_datetime($timestamp) ->format_cldr($format); say $timestamp; } exit 0; __DATA__ 20040805 18:31:00 20050106 10:54:27 20050302 01:23:35 20100808 20:00:16 20110501 18:09:44 20110909 20:02:42 20130408 18:09:03

This prints…

8/5/2004 6:31:00 PM
1/6/2005 10:54:27 AM
3/2/2005 1:23:35 AM
8/8/2010 8:00:16 PM
5/1/2011 6:09:44 PM
9/9/2011 8:02:42 PM
4/8/2013 6:09:03 PM

Jim


Comment on Re: How to format timestamps M/D/Y h:mm:ss AMPM (e.g., 4/8/2013 6:09:03 PM)?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1033397]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2015-07-30 02:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (269 votes), past polls