LoginSignup
0
0

More than 3 years have passed since last update.

Time.strptime で、%j (年中の通算日)がアレ

Last updated at Posted at 2020-07-01

他人様のコードをメンテする必要があって、コードを追ってると、%j な年月日を UNIX time に変換するのに、面倒な事やってた。

で、嫌気が差して、「ruby でも strptime あるだろ?」と適当に探すと、ビンゴ!!

問題発生

差し替える前に、テスト。

以下の様なコードを実行

$ ruby -e 'require "time" ; p Time.strptime("2003,070,12:21:51 JST", "%Y,%j,%H:%M:%S %z").to_i'
1041391311
# ↑ 2003/01/01 12:21:51 JST

問題発生。

え? %j 解釈してくれないの?

ググって見ても答えは得られず1

色々試して、、、

結論

古い rubyTime クラス(モジュール?)の .strptime は、%j 解釈してくれないっぽい2

検証では、2.7.1p83 はOKだった3

検証

以下のコードを、1.9.2p290, 2.0.0p481, 2.7.1p83 で、それぞれ実行

test.rb
require 'date'
require 'time'

# コントロール用の自作関数
def manu(t)
  arr = t.split(/[,: ]/).map(&:to_i)
  Time.mktime(arr[0],1,1,arr[2],arr[3],arr[4]) + ( arr[1] - 1) * 24 * 60 * 60
end

str = "2003,070,12:21:51 JST"
# DateTime.strptime の結果
p DateTime.strptime(str, "%Y,%j,%H:%M:%S %z").strftime("%s").to_i
# 自作関数の結果
p ( manu str ).to_i
# Timme.strptime の結果
p Time.strptime(str, "%Y,%j,%H:%M:%S %z").to_i

1.9.2 と、2.0.0 では、Time.strptime%j を解釈しない。DateTime.strptime は解釈してくれる。

1.9.2p290,2.0.0p481
$ ruby test.rb
1047352911
1047352911
1041391311  # <= 2003/01/01 12:21:51 JST

に対し、2.7.1Time.strptime も解釈してくれてる。

2.7.1p83
$ ruby test.rb
1047352911
1047352911
1047352911

ruby 版の delta みたいなのがあれば、それ読めば一発なんだろうけど、そこまでの情熱は湧かない、、、


  1. そもそも %j なんて使う事って特殊だし、、、 

  2. で、コード差し替えに関しては、 DateTime 使うのも色々と問題があり、結局検証用に作った自作コードを埋め込む形に、、、  

  3. 2.6.3p62 でもOK。 

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0