我希望以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]'
如何将“now”替换为“00:00”?使用基本Perl模块的加分点。
谢谢, 升。
答案 0 :(得分:1)
算法很简单;这是一个带有两个参数的函数,一个以分钟为单位的间隔长度和一些要返回的间隔,并返回一个包含指定间隔的arrayref,以您想要的时间格式表示:
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];
};
被称为intervals(10, 20)
,它返回以下内容:
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'
不需要Perl模块,无论是核心还是其他模块。