tags:

views:

1781

answers:

4

I need to read the system clock (time and date) and display it in a human-readable format in Perl.

Currently, I'm using the following method (which I found here):

#!/usr/local/bin/perl
@months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
@weekDays = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
$year = 1900 + $yearOffset;
$theTime = "$hour:$minute:$second, $weekDays[$dayOfWeek] $months[$month] $dayOfMonth, $year";
print $theTime; 

When you run the program, you should see a much more readable date and time like this:

9:14:42, Wed Dec 28, 2005 

This seems like it's more for illustration than for actual production code. Is there a more canonical way?

+7  A: 

Use localtime function:

In scalar context, localtime() returns the ctime(3) value:

$now_string = localtime;  # e.g., "Thu Oct 13 04:54:34 1994"
Igor Oks
Thanks, I was making it a lot harder than it needed to be. :)
Bill the Lizard
Note that 'localtime' is the (a?) US format of the local time; if you really want to provide the output, you have to work a bit harder.
Jonathan Leffler
+6  A: 

Like someone else mentioned, you can use localtime, but I would parse it with Date::Format. It'll give you the timestamp formatted in pretty much any way you need it.

Alex Fort
Thanks for the link. I'll definitely need that to put the date/time in the standard U.S. format.
Bill the Lizard
+5  A: 

You can use localtime to get the time and the POSIX module's strftime to format it.

While it'd be nice to use Date::Format's and its strftime because it uses less overhead, the POSIX module is distributed with Perl, and is thus pretty much guaranteed to be on a given system.

use POSIX;
print POSIX::strftime( "%A, %B %d, %Y", localtime());
# Should print something like Wednesday, January 28, 2009
# ...if you're using an English locale, that is.
# Note that this and Date::Format's strftime are pretty much identical
R. Bemrose
+4  A: 

As everyone else said "localtime" is how you tame date, in an easy and straight forward way.

But just to give you one more option. The DateTime module. This module has become a bit of a favorite of mine.

use DateTime;
my $dt = DateTime->now;

my $dow = $dt->day_name;
my $dom = $dt->mday;
my $month = $dt->month_abbr;
my $chr_era = $dt->year_with_christian_era;

print "Today is $dow, $month $dom $chr_era\n";

This would print "Today is Wednesday, Jan 28 2009AD". Just to show off a few of the many things it can do.

use DateTime;
print DateTime->now->ymd;

It prints out "2009-01-28"

J.J.