datetime format in perl

Perl provides nice functions to format datetime objects for us.

For example, sometimes I need to calculate the time elapsed between two timestamps,

Start time:

Sun Jun 30 2013 17:49:21

End time:

Mon Jul 01 2013 05:47:15

Basically I need to do a (Sun Jun 30 2013 17:49:21) – (Mon Jul 01 2013 05:47:15) to get the delta time.

Below is the script:

# Here you need to define a function to get the month day year hh mm ss

sub get_time {
my ($stage, $timestamp) = @_ ;
$hashstring = “Jan 01 Feb 02 Mar 03 Apr 04 May 05 Jun 06 Jul 07 Aug 08 Sep 09 Oct 10 Nov 11 Dec 12”;

if ($stage eq “Start”){
$timestamp =~ s/^\s+|\s+$//g;
($t1,$month1,$day1,$year1,$hhmmss) = split(/ /, $timestamp);
($hour1,$minute1, $seconds1) = split(/:/, $hhmmss);
$month1 = substr($hashstring, index($hashstring,$month1)+4, 2);
} elsif ($stage eq “End”){
$timestamp =~ s/^\s+|\s+$//g;
($t3,$month3,$day3,$year3,$hhmmss) = split(/ /, $timestamp);
($hour3,$minute3, $seconds3) = split(/:/, $hhmmss);
$month3 = substr($hashstring, index($hashstring,$month3)+4, 2);
}
}
# in the main sub, issue the Delta_DHMS to calculate the delta time.

($days, $hours, $minutes, $seconds) = Delta_DHMS(“$year1″,”$month1″,”$day1″,”$hour1″,”$minute1″,”$seconds1″,”$year3″,”$month3″,”$day3″,”$hour3″,”$minute3″,”$seconds3”);

#here $deltatime has the delta information in format hh:dd:mm
$deltatime = sprintf “%-45s %-30s %-30s”, $string2, $string1, $string3 ;

#more details, http://search.cpan.org/~stbey/Date-Calc-6.3/lib/Date/Calc.pod