Today, we're going to look at a custom subroutine for Perl.
Most folks who deal with Perl on a regular basis, have at some point had to deal with the system time and, in particular, the localtime() function. When this is used strictly within the program, there's no need to dress it up. However, if you're producing output for an end-user, making it more readable is always in your best interest, unless you want to answer silly questions all day ;)
The basic argument to this subroutine is the localtime() function itself, with its input derived from the built-in time function, as such:
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
Below, the subroutine, which we'll call "parse_date" will make it so that input like 18282738141843 (unix time - may not be accurate since this is just a quick representation of some amount of seconds since January 1st, 1970) looks good to the user.
Once this subroutine returns, you can print the $nice_date variable and your users will see something akin to: 03/15/07 | 09:30:47
Of course, you're free to format however you wish :) The subroutine below:
This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
sub parse_date {
my ($sec,$min,$hour,$mday,$mon,$year,$wday) = @_;
%months = qw(0 Jan 1 Feb 2 Mar 3 Apr 4 May 5 Jun 6 Jul 7 Aug 8 Sep 9 Oct 10 Nov 11 Dec);
%weekdays = qw(0 Sun 1 Mon 2 Tue 3 Wed 4 Thu 5 Fri 6 Sat);
if ( $sec < 10 ) {
$sec = "0" . $sec;
}
if ( $min < 10 ) {
$min = "0" . $min;
}
if ( $hour < 10 ) {
$hour = "0" . $hour;
}
if ( $mday < 10 ) {
$mday = "0" . $mday;
}
if ( $yday < 10 ) {
$yday = "0" . $yday;
}
$mon = $mon + 1;
if ( $mon < 10 ) {
$mon = "0" . $mon;
}
$wday = $weekdays{$wday};
$year = 1900 + $year;
$year =~ s/^..(.*)$/$1/;
$nice_date = "${mon}/${mday}/$year | ${hour}:${min}:$sec";
}
Hope this helps you out :)
, Mike
linux unix internet technology