日期处理

ZDNet软件频道 时间:2000-05-23 作者:Nathan Torkington |  我要评论(8)
本文关键词:
人类文明的历史进程是通过精确的日期和时间来刻划的, 让我们来看看Perl 程序员是如何处理日期的

常见的日期和时间操作

如果你打算计算两个时刻之间的时间段,只需将它们转换为相应的纪元秒,然后两数相减即可:

$difference_in_seconds = $later_datetime —
$earlier_datetime;

要把秒转换为分,时,或天数,只需要分别将它们除以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天后的纪元秒值为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

如果你的时区距离GMT为相差偶数个小时,这就管用了。并不是所有的时区都是很容易处理的。你所真正需要的是在你自己的时区内计算纪元秒,而不是在GMT中计算。

Perl 中的名为Time::Local的模块,可以提供两个函数 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, " ";

上一页 下一页
现在!现在!现在! 日常生活所用的日期和时间的表示

百度大联盟认证黄金会员Copyright© 1997- CNET Networks 版权所有。 ZDNet 是CNET Networks公司注册服务商标。
中华人民共和国电信与信息服务业务经营许可证编号:京ICP证010391号 京ICP备09041801号-159
京公网安备:1101082134