在Perl中,最简单的方法是将600 seconds
(表示为N
秒的十分钟)转换为00:10:00
(表示为HH:MM:SS
十分钟)?< / p>
答案 0 :(得分:7)
答案 1 :(得分:2)
取决于您对“最简单”的定义。我喜欢合理的面向未来的代码,我再也不用考虑了,这看起来像这样:
use strict;
use warnings;
use 5.10.0;
use DateTime::Duration;
use DateTime::Format::Duration;
sub duration_to_hms {
my ($duration) = @_;
my $formatter = DateTime::Format::Duration->new(
pattern => "%H:%M:%S",
normalize => 1,
);
return $formatter->format_duration($duration);
}
my $duration = DateTime::Duration->new(seconds => 600);
say duration_to_hms($duration);
答案 2 :(得分:0)
使用POSIX函数strftime()
。这是下面的完整示例...
use POSIX 'strftime';
my $seconds = 615;
print(strftime('%T', gmtime $seconds));
上面的示例输出为:
00:10:15
注意:如果小时值超过24
,此功能将无效。在这种情况下,或者如果您仅在使用POSIX工具方面有限制,则可以使用此自定义函数替换它...
sub formatSeconds {
my ($args) = @_;
my $seconds = $args->{seconds};
my ($hours, $hourremainder) = (($seconds/(60*60)), $seconds % (60*60));
my ($minutes, $seconds) = (int $hourremainder / 60, $hourremainder % 60);
($hours, $minutes, $seconds) = (sprintf("%02d", $hours), sprintf("%02d", $minutes), sprintf("%02d", $seconds));
return $hours . ':' . $minutes . ':' . $seconds;
}
formatSeconds({seconds=>642}); // output: "00:10:42"
感谢@oylenshpeegul带来使用strftime的启发!