简体   繁体   中英

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

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?

Use localtime function:

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

 $now_string = localtime; # eg, "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"

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.

以清晰易读的格式打印本地时间的最简单的单行打印语句是:

print scalar localtime (); #Output: Fri Nov 22 14:25:58 2019

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM