2 回答

TA貢獻1848條經(jīng)驗 獲得超2個贊
時間相減
use Date::Calc qw( Delta_Days );
print Delta_Days(2009,8,21,2010,8,21),"\n";
# calculate 2009-8-21 to 2010-8-21
# result 365
PERL時間操作對象
Perl中的time() 函數(shù)返回以紀(jì)元秒形式表示的當(dāng)前日期和時間。如果你打算把它轉(zhuǎn)換為字符串,就可使用gmtime() 和localtime() 函數(shù):
$now = localtime(time());
($sec, $min, $hour, $day, $mon, $year, $wday, $yday, $isdst) = localtime(time());
如果調(diào)用 localtime() 或gmtime() 時不帶參數(shù),它將自己調(diào)用time()
$now = localtime();
($sec, $min, $hour, $day, $mon, $year, $wday, $yday, $isdst) = localtime();
常見的日期和時間操作
如果你打算計算兩個時刻之間的時間段,只需將它們轉(zhuǎn)換為相應(yīng)的紀(jì)元秒,然后兩數(shù)相減即可:
$difference_in_seconds = $later_datetime -$earlier_datetime;
要把秒轉(zhuǎn)換為分,時,或天數(shù),只需要分別將它們除以60, 3600 和 86400 即可:
$difference_in_minutes = $difference_in_seconds / 60;
$difference_in_hours = $difference_in_seconds / 3600;
$difference_in_day = $difference_in_seconds / 86400;
反過來做,你也可以回答如下問題:”4天后是幾號?”:
$then = time() + 86400 * 4;
print scalar localtime $then;
它給出的答案精確到秒。例如,如果4天后的紀(jì)元秒值為932836935, 你可以輸出日期的字符串如下;
Sat Jul 24 11:23:17 1999
如果你打算輸出那個日期的午夜時分 (如”Sat Jul 24 00:00:00 1999〃) 使用如下模塊:$then = $then - $then % 86400; # 去掉那個日期的尾巴
類似地,你可以用四舍五入法,輸出最靠近午夜時分的日期:
$then += 43200; # add on half a day
$then = $then - $then % 86400;# truncate to the day
如果你的時區(qū)距離GMT為相差偶數(shù)個小時,這就管用了。并不是所有的時區(qū)都是很容易處理的。你所真正需要的是在你自己的時區(qū)內(nèi)計算紀(jì)元秒,而不是在GMT中計算。
Perl 中的名為Time::Local的模塊,可以提供兩個函數(shù) timelocal() 和timegm()。其返回值同 localtime() 和gmtime() 一樣。
use Time::Local;
$then = time() + 4*86400;
$then = timegm localtime $then;
# local epoch seconds
$then -= $then % 86400;
# truncate to the day
$then = timelocal gmtime $then;
# back to gmt epoch seconds
print scalar localtime $then, “\n”;
- 2 回答
- 0 關(guān)注
- 847 瀏覽
添加回答
舉報