-2

我想生成一个格式为 hh:mm 的时间数组,给定时间间隔和时间点数,从零开始。因此,10 分钟的 3 个时间点将产生 (00:00, 00:10, 00:20)。我发现了这个非常好的片段,用于从现在开始增加和格式化时间:

perl -e '@d=localtime time() + 600 - localtime time(); 
printf "%02d:%02d%s\n",$d[2]%12,$d[1]'

如何将“现在”替换为“00:00”?使用基本 Perl 模块的奖励积分。

谢谢,L。

4

1 回答 1

1

The algorithm is simple enough; here's a function that takes two arguments, an interval length in minutes and a number of intervals to return, and returns an arrayref containing the specified intervals, expressed in your desired time format:

sub intervals {
    my $interval = shift(); # interval length in minutes
    my $n_points = shift(); # number of intervals to return
    die "intervals() takes two arguments\n"
            unless $interval and $n_points;

    my @now_tm = localtime();

    # check DST delta per @ikegami
    my $dst_delta = 0;
    my @yesterday_tm = localtime(time() - 86400);
    if ($yesterday_tm[8] && !$now_tm[8]) {
            # "fall back" - today is an hour shorter
            $dst_delta = -3600;
    }
    elsif (!$yesterday_tm[8] && $now_tm[8]) {
            # "spring forward" - today is an hour longer
            $dst_delta = 3600;
    };

    # find timestamp for 00:00 today
    my $now_ts = time();
    my $then_ts = $now_ts
            + $dst_delta          # apply any dst correction required 
            - ($now_tm[2] * 3600) # subtract hours since midnight
            - ($now_tm[1] * 60)   # ...and minutes
            - $now_tm[0];         # ...and seconds

    # generate actual intervals, starting at midnight
    my @interval_times = ();
    for (my $point = 0; $point < $n_points; $point++) {
            my $interval_ts = $then_ts + (($interval * 60) * $point);
            my @interval_tm = localtime($interval_ts);
            my $interval_formatted = sprintf("%0.2d:%0.2d", 
                                             $interval_tm[2],
                                             $interval_tm[1]);
            push @interval_times, $interval_formatted;
    };

    return [@interval_times];
};

Called as intervals(10, 20), it returns the following:

0  ARRAY(0xd284e40)
   0  '00:00'
   1  '00:10'
   2  '00:20'
   3  '00:30'
   4  '00:40'
   5  '00:50'
   6  '01:00'
   7  '01:10'
   8  '01:20'
   9  '01:30'
   10  '01:40'
   11  '01:50'
   12  '02:00'
   13  '02:10'
   14  '02:20'
   15  '02:30'
   16  '02:40'
   17  '02:50'
   18  '03:00'
   19  '03:10'

And no Perl modules required, whether core or otherwise.

于 2013-07-25T19:35:40.633 回答