18

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 Perl? I prefer native functions.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
Brian
  • 191
  • 1
  • 1
  • 4
  • 1
    While I understand your preference for native/core modules, DateTime and a few related formatters are absolutely worth the effort to get into your kit. http://search.cpan.org/dist/DateTime/ – daotoad Jan 28 '10 at 15:22

3 Answers3

39

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.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
  • 1
    Judging from the unambiguous `01/13/2010` in the question, Brian seems to want a format of `"%m/%d/...` or even `"%D %T"`. – Greg Bacon Jan 27 '10 at 19:10
  • @gbacon `%D %T` did not work on `perl` 5.10.1 on Windows (it did on Linux), I decided to play safe. Thanks for noticing that I accidentally swapped `%m` and `%d`. – Sinan Ünür Jan 27 '10 at 19:14
  • 2
    But don't avoid learning about `localtime` (or `sprintf`) either. – mob Jan 27 '10 at 19:22
  • While using POSIX is cool and The Right Thing, I read somewhere that the module is quite resource-hungry. So I guess you might want to sacrifice it in some cases... – Alois Mahdal Jul 15 '12 at 18:36
1

Try the Date::Format formatting subroutines from CPAN.

Wolf
  • 9,679
  • 7
  • 62
  • 108
Diego Dias
  • 21,634
  • 6
  • 33
  • 36
1

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
sdc
  • 2,603
  • 1
  • 27
  • 40