开发者

How can I format a timestamp in Perl?

I would like to get this timestamps formatting:

01/13/2010 20:42:03 - -

Where it's always 2 digits for the number except for the year, where it's 4 digits. And it's based on a 24-hour clock.

How can I do this in P开发者_开发问答erl? I prefer native functions.


POSIX provides strftime:

$ perl -MPOSIX -we 'print POSIX::strftime("%m/%d/%Y %H:%M:%S\n", localtime)'
01/27/2010 14:02:34

You might be tempted to write something like:

my ($sec, $min, $hr, $day, $mon, $year) = localtime;
printf("%02d/%02d/%04d %02d:%02d:%02d\n", 
       $day, $mon + 1, 1900 + $year, $hr, $min, $sec);

as a means of avoiding POSIX. Don't! AFAIK, POSIX.pm has been in the core since 1996 or 1997.


This is a subroutine that I use. It allows you to get the date time stamp in whichever format you prefer.

#! /usr/bin/perl
use strict;
use warnings;

use POSIX;
use POSIX qw(strftime);

sub getTime 
{
    my $format = $_[0] || '%Y%m%d %I:%M:%S %p'; #default format: 20160801 10:48:03 AM
    my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime(time);
    return strftime($format, $sec, $min, $hour, $wday, $mon, $year, $mday);
}

# Usage examples
print getTime()."\n";                    #20160801 10:48:03 AM
print getTime('%I:%M:%S %p')."\n";       #10:48:03 AM
print getTime('%A, %B %d, %Y')."\n";     #Monday, August 01, 2016
print getTime('%Y%m%d %H:%M:%S')."\n";   #20160801 10:48:03


Try the Date::Format formatting subroutines from CPAN.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜