How do you read the system time and date in Perl?

Use localtime function:

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

$now_string = localtime;  # e.g., "Thu Oct 13 04:54:34 1994"

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

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"

Tags:

Datetime

Perl