Home: Perl Programming Help: Frequently Asked Questions:
How do I get the date and time?



sleuth
Enthusiast

Dec 12, 2000, 5:05 PM


Views: 11253
How do I get the date and time?

 There are many different methods to getting the data & time in perl, if your looking to just get the full date and time, you could do this:

$date_time = localtime;
print "$date_time";

OUTPUT:

Tue Dec 12 16:23:58 2000

To get each element of localtime and make your own format, just use this code:

@date_time = localtime;
$date = "@date_time";
($sec, $min, $hours, $mday, $month, $year, $wday, $yday, $isdst) = split(/\s/, $date);
$year += 1900;

All that last line does is bring the year up to 2000, since it's the year 2000 right now.

Other variables like the $month, start at 0, being January, to turn these numbers into the name of the months, you could make an array of months in the correct order and just call on the array value to print the month's name. Like so:

(@names) = ('January','February','March','April','May','June','July','August','September','October','November','December');
$month_name = "$names[$month]";
print "$month_name";

Output:

December

Since this was written in December.

I have attached a small txt file including a chart of the variables and there meanings to help you.

Also, you can use "gmtime" instead of "localtime" to get your date's and time's based on GMT time.

That concludes getting the date and time in perl.

Sleuth



Jasmine
Administrator

Jan 13, 2001, 1:59 PM


Views: 11186
Re: How do I get the date and time? [CORRECTED]

FAQ Correction:


Code
($sec, $min, $hours, $mday, $month, $year, $wday, $yday, $isdst) = localtime();   
# or localtime(time) -- time is the default value
$year += 1900; # add 1900 to year because $year is the current year minus 1900
$month++; # increment because month index starts at 0



sleuth
Enthusiast

Jan 15, 2001, 3:04 PM


Views: 11175
Re: How do I get the date and time? [CORRECTED]

 
What did I do wrong?



Jasmine
Administrator

Jan 15, 2001, 4:21 PM


Views: 11172
Re: How do I get the date and time? [CORRECTED]

There wasn't anything "wrong", But the assignments of @date_time and $date were just a roundabout way of doing localtime(time) and more prone to user-errors. IMHO, of course :)





sleuth
Enthusiast

Jan 18, 2001, 1:39 PM


Views: 11161
Re: How do I get the date and time? [CORRECTED]

 
*Hugs*



Jasmine
Administrator

Jan 18, 2001, 5:38 PM


Views: 11159
Re: How do I get the date and time? [CORRECTED]

*grin*