向此代码添加毫秒的最有效方法是什么?

向此代码添加毫秒的最有效方法是什么?
#-----------------------------------------------------------------------------
#
# Get time string
#
#-----------------------------------------------------------------------------
#
sub formatTime
    {
    my ( $seconds )  = @_;

    my( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
                                localtime( $seconds );
    $year += 1900;
    $mon += 1;

    return ( sprintf "%02d/%02d/%04d %02d:%02d:%02d",
                $mday,$mon,$year,$hour,$min,$sec );
    }

#-----------------------------------------------------------------------------
#
# Extract time from the string
#
#-----------------------------------------------------------------------------
#
sub extractTime
    {
    my ( $edate, $time ) = @_;

    my $date =  $1 if ($edate =~ /(\d+\/\d+\/\d+)/);    # remove leading '[' etc.
    my ( $mday, $mon, $year ) = split( /\//, $date );
    my ( $hour,$min, $sec ) = split( /:/, $time );

    return (timelocal( $sec, $min, $hour, $mday, ($mon - 1), ($year - 1900 )));
    }

答案1

为了使您的函数获得更高的精度formatTime,您需要以毫秒为单位,而不是秒。您无法采用四舍五入的秒数并使其更精确。

由于 localtime() 只接受自纪元以来的秒数,因此您需要将传入的毫秒数转换为秒数。这是一个例子:

use POSIX qw(floor);

sub formatTime {
    my ( $milliseconds )  = @_;

    my $seconds = floor($milliseconds / 1000);
    my $msec = $milliseconds % 1000;

    my( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
                                localtime( $seconds );
    $year += 1900;
    $mon += 1;

    return ( sprintf "%02d/%02d/%04d %02d:%02d:%02d:%04d",
                $mday,$mon,$year,$hour,$min,$sec,$msec );
}

另一种选择是使用约会时间。如果以小数形式传递秒,则可以创建精度更高的 DateTime 对象:

use DateTime;

sub formatTime {
    my ( $seconds ) = @_;
    my $dt = DateTime->from_epoch( epoch => $seconds );
    # ....
}

相关内容