Showing posts with label local date. Show all posts
Showing posts with label local date. Show all posts

Wednesday, August 1, 2012

PERL Date function

Basic perl script the extract system date and prints different format.

getTime() function takes a numeric argurment which determines the date format.

Function can be used as  '$variable = &getTime(x)' , where x can any number from 0 - 4 (which ever formate you want) and '$variable' takes the return value.

----------------------------------------------------------------

#!/usr/bin/perl

sub main {
        my $curr_date;
        my $count;
        for ($count=0;$count <=4;$count++){
                $curr_date = getTime($count);
                print "Current date : $curr_date\n";
        }

}

&main();

sub getTime {
        my $timeFormat = shift;
        my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
        my @weekDays = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
        my ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
        my $year = 1900 + $yearOffset;
        my $monthss = $month +1 ;
        my $theTime = "";
        if ($timeFormat == 0){
                $theTime = "$hour:$minute:$second, $weekDays[$dayOfWeek] $months[$month] $dayOfMonth, $year";
        }
        elsif ($timeFormat == 1){
                $theTime = "$months[$month] $dayOfMonth, $year";
        }
        elsif ($timeFormat == 2 ){
                my $paddedHour = sprintf("%02d", $hour);
                my $paddedMin = sprintf("%02d", $minute);
                my $paddedSec = sprintf("%02d", $second);
                $theTime = "${paddedHour}:${paddedMin}:${paddedSec}";


        }
        elsif ($timeFormat == 3 ){
                my $paddedMonth = sprintf("%02d", $monthss);
                my $paddedDay = sprintf("%02d", $dayOfMonth);
                $theTime = "${year}-${paddedMonth}-${paddedDay}";

        }
        elsif ($timeFormat == 4 ){
                my $paddedMonth = sprintf("%02d", $monthss);
                my $paddedDay = sprintf("%02d", $dayOfMonth);
                $theTime = "${paddedMonth}/${paddedDay}";

        }
        return $theTime;