#!/usr/bin/perl # # odate - A date command with offset option # # A. Stigand # William Favorite # # Works just like date, but also accepts -o option # # Use this to find the AIX error log messages in the last 24 hours: # errpt -s `./odate -o -1d "+%m%d%H%M%y"` # I added this option to get the same thing # errpt -s `./odate -o -1d --errpt use POSIX; ### Globals my $t; # Time - seconds since Unix epoch my $fmt; # The format string to strftime() my $naio; # Next Argument Is Offset (This arg is -o) my $offset; # The offset in seconds ### Set default values $fmt = "%a %b %d %H:%M:%S %Z %Y"; $naio = 0; $offset = 0; ### Parse input while (@ARGV) { my $arg = shift @ARGV; if ( $naio ) { $naio = 0; $offset += parse_offset($arg); } elsif ( $arg =~ /-o/ ) { $naio = 1; } elsif ( $arg =~ /-h/ ) { usage(); } elsif ( $arg =~ /--errpt/ ) { $fmt = "%m%d%H%M%y" } elsif ( $arg =~ /^\+.+/ ) { $arg =~ s/^\+//; $fmt = $arg; } else { print "ERROR: Input not understood. Use -h for help.\n"; exit 1; } } $t = time() + $offset; print POSIX::strftime( "$fmt\n", localtime($t)); ################################################################################ # Print the usage / help information sub usage { print "odate - A date command with offset option\n"; print " Usage: odate [ -h | [[-o ][-o ...] [format_string]] ]\n"; print " Offsets are in seconds, unless otherwise specified.\n"; print " Multiple offsets can be specified (meaning you cannot stack\n"; print " an offset such as -o 1h30m but can specify -o 1h -o 30m)\n"; print " The --errpt flag is a synonym for +%m%d%H%M%y\n"; exit 0; } ################################################################################ # Turn a formatted offset string into seconds (ie: 122 = parse_offset("2m2s"); ) sub parse_offset { my $totalseconds = 0; my $negative = 1; my ( $raw_offset ) = @_; # Look for a leading negative sign if ( $raw_offset =~ /^-[0-9]+.*/ ) { $negative = -1; # Make note that we are negative $raw_offset =~ s/^-//; # Strip off the negative sign } # Look for a leading positive sign if ( $raw_offset =~ /^\+[0-9]+.*/ ) { $raw_offset =~ s/^\+//; # Strip off the positive sign } if ( $raw_offset =~ /^[0-9]+$/ ) { return $raw_offset * $negative; } else { # Note: I cheated here. If the user wishes to specify 3d2h1m then # they must do this: -o 3d -o 2h -o 1m # I did not want to spend 1d5h writing functionality that most # users will never use. if ( $raw_offset =~ /^[0-9]+[Ww]$/ ) { $raw_offset =~ s/[Ww]$//; return $raw_offset * 7 * 24 * 60 * 60 * $negative; } elsif ( $raw_offset =~ /^[0-9]+[Dd]$/ ) { $raw_offset =~ s/[Dd]$//; return $raw_offset * 24 * 60 * 60 * $negative; } elsif ( $raw_offset =~ /^[0-9]+[Hh]$/ ) { $raw_offset =~ s/[Hh]$//; return $raw_offset * 60 * 60 * $negative; } elsif ( $raw_offset =~ /^[0-9]+[Mm]$/ ) { $raw_offset =~ s/[Mm]$//; return $raw_offset * 60 * $negative; } elsif ( $raw_offset =~ /^[0-9]+[Ss]$/ ) { $raw_offset =~ s/[Ss]$//; return $raw_offset * $negative; } else { return 0; } } }