時間差を計算するプログラム
プログラミング::tools
序
最近2つの時刻の経過を分で計算する必要が出てきた。
ウェブサービスでもそういったものはあったりするが、入力しづらいし面倒なので書くことにする。
まずはRubyで
いつもどおりのRuby。
#!/bin/ruby
def usage
abort "timediff.rb from[,] to"
end
ARGV[0] =~ /^(\d{1,2}):(\d{2}),?$/ or usage
= $1.to_i * 60 + $2.to_i
t_from
ARGV[1] =~ /^(\d{1,2}):(\d{2})$/ or usage
= $1.to_i * 60 + $2.to_i
t_to
if t_to < t_from
+= 60 * 24
t_to end
puts t_to - t_from
話自体は非常に単純で、時間を分に直した分と分を足すだけである。 日付をまたいでいる場合のために、終端のほうが小さいなら24時間分足す。
Zshで
これくらいならZshでも簡単に書ける。
#!/bin/zsh
usage() {
print "timediff.zsh from[,] to" >&2
exit 1
}
[[ $1 == ([0-9]|)[0-9]:[0-9][0-9](,|) ]] || usage
typeset -i t_from=$(( ${1%%:*} * 60 + ${${1##*:}#,} ))
[[ $2 == ([0-9]|)[0-9]:[0-9][0-9] ]] || usage
typeset -i t_to=$(( ${2%%:*} * 60 + ${${2##*:}#,} ))
(( t_from > t_to )) && t_to+=$((24 * 60))
print $(( t_to - t_from ))
注意点としてtypeset -i
しておかないと+=
が文字列結合になって日付をまたいだときに大惨事になる。
代わりに(( t_to += 24 * 60 ))
としてもいいが、それにしてもtypeset -i
はしておいたほうがいい。
Perlで
Unix系プラットフォームで移植性の高い選択肢であるPerl。 この手のやつは非常に得意。
#!/bin/perl
sub usage() {
print "timediff.pl from[,] to\n";
exit 1;
}
$ARGV[0] =~ /^(\d{1,2}):(\d{2}),?$/ || usage;
my $t_from = $1 * 60 + $2;
$ARGV[1] =~ /^(\d{1,2}):(\d{2})$/ || usage;
my $t_to = $1 * 60 + $2;
if ($t_to < $t_from) {
$t_to += 60 * 24;
}
print $t_to - $t_from, "\n";