计算时间的程序
program to calculate the time
我想计算当前时间并加上 2 分钟,然后按以下格式打印输出。 HH:MM。我在网上搜索了一下,才知道有很多 CPAN 模块可以用来实现这个。但我想在没有 cpan 模块的情况下做到这一点。
$current_time = time();
$new_time = $current_time + (2*60); // adding two minutes
print( ' the time is ' . $ new_time ) ;
Output : the time is 1424906904
上网查了下才知道需要用到POSIXperl接口把时间打印成合适的格式。但是我想知道是否有办法在不使用任何 cpan 模块的情况下做到这一点。
您可以使用 localtime
:
print scalar localtime($current_time);
或者你可以 运行 localtime
的 return 值通过 POSIX::strftime
(作为核心模块与 Perl 一起分发):
use POSIX qw(strftime);
print strftime('%Y-%m-%d %H:%M:%S', localtime $current_time);
localtime 很容易做到这一点。小时、分钟和秒是返回的第 2、第 1 和第 0 个值。例如:
my ($sec, $min, $hours) = localtime(time()+120); # add 120 seconds
printf "%02d:%02d:%02d\n", $hours, $min, $sec;
Time::Piece and Time::Seconds 自 2007 年以来已包含在所有 Perl 安装中。
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use Time::Piece;
use Time::Seconds;
my $time = localtime;
$time += 2 * ONE_MINUTE;
say $time->strftime('%H:%M');
我想计算当前时间并加上 2 分钟,然后按以下格式打印输出。 HH:MM。我在网上搜索了一下,才知道有很多 CPAN 模块可以用来实现这个。但我想在没有 cpan 模块的情况下做到这一点。
$current_time = time();
$new_time = $current_time + (2*60); // adding two minutes
print( ' the time is ' . $ new_time ) ;
Output : the time is 1424906904
上网查了下才知道需要用到POSIXperl接口把时间打印成合适的格式。但是我想知道是否有办法在不使用任何 cpan 模块的情况下做到这一点。
您可以使用 localtime
:
print scalar localtime($current_time);
或者你可以 运行 localtime
的 return 值通过 POSIX::strftime
(作为核心模块与 Perl 一起分发):
use POSIX qw(strftime);
print strftime('%Y-%m-%d %H:%M:%S', localtime $current_time);
localtime 很容易做到这一点。小时、分钟和秒是返回的第 2、第 1 和第 0 个值。例如:
my ($sec, $min, $hours) = localtime(time()+120); # add 120 seconds
printf "%02d:%02d:%02d\n", $hours, $min, $sec;
Time::Piece and Time::Seconds 自 2007 年以来已包含在所有 Perl 安装中。
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use Time::Piece;
use Time::Seconds;
my $time = localtime;
$time += 2 * ONE_MINUTE;
say $time->strftime('%H:%M');