【问题标题】:How to get time difference in perl?如何在perl中获得时差?
【发布时间】:2014-11-28 22:04:06
【问题描述】:

我有两个仅包含时间戳的字符串,看起来像这样 - my $t = "2014-11-28 00:00:00.000"; 我如何获得可读时间(天、小时、分钟、秒)而不是秒之间的时差。我是新手,我在做这件事时遇到了很大的困难。每篇博客或文章都在告诉我做不同的事情。有些事情无法完成,因为我没有模块。我什至无法将模块安装到 perl 中,因为我正在使用的计算机上有许多珍珠版本。所以, cpan > install some::modlue 没有帮助。

请教我如何做到这一点。 请尝试使用核心 perl。否则我将不得不花更多时间将 perl 模块安装到正确的 perl 中

我一开始就做了一些代码,但它错误且无用 -

use strict;
use warnings;
use Time::Local;

sub secondsToTime{

    my $inSeconds = shift;
    my $days = int($inSeconds/(24*60*60));
    my $hours = ($inSeconds/(60*60))%24;
    my $mins = ($inSeconds/60)%60;
    my $sec = $inSeconds%60;
    my $time = "$days days, $hours hours, $mins mins, $sec seconds";
    return $time;
}

# EXAMPLE timelocal( $sec, $min, $hour, $mday, $mon, $year );
my @today = localtime();
print "@today\n";
my $currentTime = timelocal(@today);

#my @t = (0, 00, 13, 28, 11, 2014);
#$currentTime = timelocal(@t);
my @birthday = (0, 00, 12, 28, 11, 2014); 
my $birthTime = timelocal(@birthday);
my $sec = ($currentTime - $birthTime);
my $time = secondsToTime($sec);

print "My age = $time\n";

【问题讨论】:

  • 时间戳在哪个时区?
  • 您需要支持哪些 perl 版本?
  • @ysth - Perl 5.20。时间戳将采用 MST 或 PST。有一些考虑时间戳的东西会很好。谢谢。
  • 每个人都建议用一个模块来做的原因是,做对了很难,运行cpan(或cpanp)并安装相关模块比它容易得多从第一原则编写代码来完成这项工作。 Perl 程序员的首要品质之一是懒惰,即重用其他人已经完成的工作。您安装的最简单的模块可能是POSIX::strptime。最全面的无疑是(广泛的)DateTime 系列模块。
  • @Borodin: App::cpanminus 安装 cpanm;我想这就是你的意思,不是吗?

标签: perl


【解决方案1】:

您似乎不想帮助我们了解您需要什么。

此程序将打印2014-11-28T00:00:00.000Z2014-11-28T00:00:00.000Z 之间的差异。

use strict;
use warnings;

use Time::Piece;

my $start = '2014-11-28T00:00:00.000Z';
my $end   = '2014-11-28T00:00:00.000Z';

print difference($start, $end);

sub difference {
  my ($beg, $end) = map Time::Piece->strptime(s/\.\d*Z?\z//r, '%Y-%m-%dT%H:%M:%S'), @_;
  ($end-$beg)->pretty;
}

输出

0 seconds

【讨论】:

  • 在@INC 中找不到 Time/Piece.pm(@INC 包含:
  • @smalls:那么你已经完全搞砸了你的 Perl 安装。 Time::Piece 自 5.010 版以来一直是核心 Perl 的一部分,如果您正在运行 5.20 并且它找不到它,那么就会出现严重问题。您需要删除 一切 并从头开始。如果您真的需要保留多个 Perl 版本,请查看 App::perlbrew
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-24
  • 2013-04-07
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
相关资源
最近更新 更多