dt
#!/usr/bin/perl
use Getopt::Long;
use POSIX;
# ---------------------------------------------------------------------------
sub main
{
my ($delta, $format, $offset);
GetOptions("-when=s" => $offset,
"-format=s" => $format);
if ($format eq "")
{
$format = "%a %b %e %H:%M:%S %Y";
}
$delta = parse_offset($offset);
printf("%sn", strftime($format, localtime(time + $delta)));
}
# ---------------------------------------------------------------------------
# offsets to handle:
# 'today'
# 'tomorrow'
# 'yesterday'
# '(last|next) (week|month|year)'
# '(+|-)3 (seconds|minutes|hours|days|weeks|months|years)'
# '(+|-)((HH:)MM:)SS'
sub parse_offset
{
my ($offset);
($offset) = @_;
if ($offset =~ /^s*$/)
{
$rval = 0;
}
elsif ($offset =~ /tomorrow/)
{
$rval = 24 * 3600;
}
elsif ($offset =~ /yesterday/)
{
$rval = -24 * 3600;
}
elsif ($offset =~ /today/)
{
$rval = 0;
}
elsif ($offset =~ /next/)
{
$rval = parse_unit($offset, 1);
}
elsif ($offset =~ /last/)
{
$rval = -1 * parse_unit($offset, 1);
}
elsif ($offset =~ /(second|minute|hour|day|month|year)/)
{
($count) = ($offset =~ /(-?d+)/);
$rval = $count * parse_unit($offset, $count);
}
elsif ($offset =~ /(-|+)?(d+s+)?(dd:)?(dd:)?(dd)/)
{
$sign = ;
$days = ;
$hours = ;
$minutes = ;
$seconds = ;
$rval = $days;
$rval = 24*$rval + $hours;
$rval = 60*$rval + $minutes;
$rval = 60*$rval + $seconds;
$rval = -1 * $rval if ($sign eq "-");
}
else
{
print("Unrecognized offset: '$offset'n");
exit(1);
}
return $rval;
}
# ---------------------------------------------------------------------------
# return the number of seconds represented by the recognized unit
sub parse_unit
{
my ($offset, $count);
($offset, $count) = @_;
if ($offset =~ /second/)
{
$rval = 1;
}
elsif ($offset =~ /minute/)
{
$rval = 60;
}
elsif ($offset =~ /hour/)
{
$rval = 60 * 60;
}
elsif ($offset =~ /day/)
{
$rval = 24 * 60 * 60;
}
elsif ($offset =~ /month/)
{
$now = time();
@now = localtime($now);
@then = @now;
$then[4] += $count;
$rval = mktime(@then) - $now;
}
elsif ($offset =~ /year/)
{
$rval = 365.25 * 24 * 60 * 60;
}
return $rval;
}
# ---------------------------------------------------------------------------
main();
Comments (0)
You don't have permission to comment on this page.