On many Unix systems, time is kept in seconds elapsed since Jan 1, 1970. Thus, date and time are fundamentally just an integer value. Perl contains a number of functions and modules that convert the time integer value into different formats.
The time( )
function returns the integer value of the current time (that is, the time on the machine on which the code executes). On Friday, March 5, 2004 at 7:05:17pm, calling
$t = time( ); print $t . "\n";
printed 1078535117
.
To format the date as a text string, the following code
$t = localtime( ); print $t . "\n";
will print the current date in this manner: Fri Mar 5 19:10:33 2004
.
When localtime( )
is called without an integer parameter, it will return the current system time. If it is given an integer, it will return the format string of the time and date represented by that integer.
$t = localtime(50000); print $t . "\n";
will print Thu Jan 1 07:53:20 1970
.
If dates are to be stored (in a file, for example), it is more efficient to use the integer value than the formatted string, since an integer takes up less space. Likewise, operations on a date--like sorting or calculating other dates--are easier to do with an integer than a string value.
To calculate past or future dates, subtract or add the appropriate number of seconds.
#!/usr/bin/perl $t = time( ); print "\nCurrent system time: " . $t . "\n"; $t = localtime( ); print "Current local time: " . $t . "\n"; $t = localtime(time() - (60 * 60 * 24)); # subtract number of seconds for 24 hrs. print "Local time 24 hrs. ago: " . $t . "\n"; $t = localtime(time() + (60 * 60 * 24 * 6)); # add number of seconds for 6 days print "Local time next week: " . $t . "\n\n";