Times a current time "12/DEC/2001:12:23:12" (apache Time) and parses then diplays it as epoch then converts back -JoeCool
#!/usr/bin/perl # # Epoch.pl # # Convert current time to epoch and back # # Joe Henderson # # 1.0 -> 1Dec01 # Born # # 1.1 -> 9Dec01 # Returned Epoch # # 1.2 -> 10Dec01 # Added Subroutines # system("clear"); #Clear Screen use Time::Local; #Using Time Mod $date = "17/Nov/2002:12:11:37"; #Manual Date $etime = &epoch($date); #Getting Epoch Number ($eday, $emon, $eyear, $ehr, $emin, $esec) = &etime($etime); #Convert +Back Time print "Date Entered: $date\n"; print "Epoch Date: $etime\n"; print "Date: $eday $emon$eyear $ehr:$emin:$esec\n"; exit; ##Subroutines sub etime ##Change from Epoch Time to DMYHMS { my $eptime = @_[0]; my %months ('1',Jan,'2',Feb,'3',Mar,'4',Apr,'5',May, '6',Jun,'7',Jul,'8',Aug,'9',Sep,'10',Oct,'11',Nov, '12',Dec); ($esec, $emin, $ehr, $eday, $emon, $eyear) = localtime($eptime); $eyear += 1900; $emon += 1; #Time Zone Change (Zulu) $emon = $emonths{$emon}; return ($eday, $emon, $eyear, $ehr, $emin, $esec); } sub epoch ##Change from DMYHMS to Epoch Time { my $date = @_[0]; %months = ('Jan',1,'Feb',2,'Mar',3,'Apr',4,'May',5, 'Jun',6,'Jul',7,'Aug',8,'Sep',9,'Oct',10, 'Nov',11,'Dec',12); $date =~ tr/\[//d; @dates = split(/\:/, $date); @mons = split(/\//, $dates[0]); $year = $mons[2]; $mon = $mons[1]; $day = $mons[0]; $hr = $dates[1]; $min = $dates[2]; $sec = $dates[3]; my $mon = $months{$mon}; if(!($mon < 1) || ($mon > 12)) ##Bad Dates Chk { $time = timelocal($sec, $min, $hr, $day, $mon-1, $year-1900); #converts to Epoch chomp($time); } return $time; chomp($time); return $time; }

Replies are listed 'Best First'.
Re: Epoch Conversion
by ArjanM (Novice) on Dec 14, 2001 at 21:06 UTC
    Nice piece of code. (It just misses a '=' at the line where %months is defined..)
Re: Epoch Conversion
by grinder (Bishop) on Dec 23, 2001 at 18:30 UTC
    Accepting input for $date should be written as

    my $date = shift || '12/DEC/2001:17:23:09';

    The means you can enter a value on the command line without having to edit your script, and if nothing is supplied a default value will be used.

    The creation of the %month hash is better written using the pair operator =>. Also, since you never modify it, it is even better to define it as a constant. And finally, through the wonders of human perception finding it easier to scan columns, the betterer way would be something like:

    use constant MONTH => { Jan => 1, Apr => 4, Jul => 7, Oct => 10, Fen => 2, May => 5, Aug => 8, Nov => 11, Mar => 3, Jun => 6, Sep => 9, Dec => 12, }; ... my $mon = MONTH->{$mon};

    Minor usability quibble: programs that gratuitously clear the screen make me want to reach for the bazooka. Don't do it, or at least do it in a portable way, and don't do it if the code is not being run from a tty.

    --
    g r i n d e r
    just another bofh

    print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u';