最近工作需要perl进行一些操作,其中要用到频繁的时间的换算(其实就是向前或者向后N天的计算^_^),没有去找CPAN,于是自己写了几个笨方法,凑合用吧
-----------------------
#!/usr/bin/perl -w
#created by rick 2005-03-16
#some shared method
package include;
use POSIX;
use Time::Local;
#log
sub w2log{
open(LOG,">> $-[0]");
my $msg = "[".now()."] ".$-[1]."\n";
print $msg;
print LOG $msg;
close(LOG);
}
#now
sub now{
my $now_string = strftime "%Y-%m-%d %H:%M:%S", localtime;
return $now_string;
}
#get time
sub getTargetDate{
#e.g. getTargetDate("2005-03-17","-1")=2005-03-16 00:00:00
my $date=$-[0];
my $gap=$-[1]+0;
if ($-[0]=~/:/==1) {#"2005-03-18 16:33:28"
}else {#"2005-03-18"
$date=$-[0]." 00:00:00";
}
$gap=$gap*24*60*60;
my $target_date=str2time($date)+$gap;
return time2str($target_date);
}
#return the seconds
sub str2time{
#str2time("2005-03-18 16:33:28")
#return 12312323second:
my $str=$-[0];
my @arr = split(/[- :]/,$str);
my $result = timelocal($arr[5],$arr[4],$arr[3],$arr[2],$arr[1]-1,$arr[0]);
return $result;
}
#return date string
sub time2str{
#time2str(12312323)
#return "2005-03-18 16:33:28"
my $the_date= strftime "%Y-%m-%d %H:%M:%S\n", localtime($-[0]);
chomp($the_date);
return $the_date;
}
1;