Wednesday, April 10, 2013

Perl - 6 examples to fetch date / time without Linux date command

How to fetch date and time related stuff within in Perl?
   Sometimes, Perl developers resort to using of Unix system date command to fetch a date or time within Perl script. This is not needed at all since Perl itself has a set of built-ins using which dates and epoch can be retrieved easily without using the system date command. In this article, let us see how to simulate the date related commands in Perl.

1. Getting the date command output:
Linux command:
$ date
To get the date command like output in Perl:
my $x=localtime;
print $x;
   localtime is a Perl built-in, which when called without any arguments returns the current date and time. The above program will return an output like this:
Wed Apr 10 15:54:10 2013
2. Extract only the hour,minute and seconds from the date command:
$ date '+%H%M%S'
my ($s,$m,$h)=localtime;
print "$h$m$s";
localtime built-in depends on the context in which it is being used:
In scalar context, returns the date and time like the Unix date command.
In list context, returns a list of values : seconds,minutes,hour,day,month(0-11),year,and so on. In the above example, only the seconds, minutes and hours are stored.

3. Get the Unix(epoch) time:
$ date '+%s'
my $tm=time;
print $tm;
    time is a perl built-in which gives the Unix Time (epoch).

4. Get yesterday's date:
$ date -d "yesterday" '+%y%m%d'
use POSIX qw(strftime);

my $x=strftime("%y%m%d",localtime(time-86400));
print $x;
2 things to note:
a. localtime built-in can take a Unix time as an argument and return the date/time for the specific Unix time. In other words,  $x=localtime is same as $x=localtime(time) . By subtracting, time with 86400(24*60*60), we get the Unix time of yesterday.
b. strftime is a function which takes a localtime as argument, and formats the result as a string. The format specifiers are similar to the system date command.

5. Get Unix time(epoch) of yesterday's date:
$ date -d "yesterday" '+%s'
my $tm=mktime(localtime(time-86400));
print $tm;
  mktime is another Perl built-in which can calculate the Unix time for a given localtime. This above snippet calculates the Unix time for the last day.
6. Get epoch of a specific date/time:
$ date -d "08 May 2012 11AM 30minutes" '+%s'
my $tm=mktime(0,30,11,8,4,112);
print $tm;
   Since mktime takes the input of the format of localtime command's output, by providing the appropriate date and time as arguments to the mktime, the Unix time can be calculated for any pre-defined date and time.

No comments:

Post a Comment