I had to maintain someone else's code, and when I followed the code, it was a hassle to convert the % j date to ʻUNIX time`.
Then, when I was disgusted and searched for " ruby but strptime?", Bingo !!
Test before replacing.
Execute the following code
$ 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
a problem occured.
Eh? % J Can you interpret it?
I couldn't get an answer even if I looked at Gugu [^ 1]
[^ 1]: It's special to use % j in the first place ...
Try various things ...
The .strptime of the Time class (module?) Of the old ruby doesn't seem to interpret% j [^ 2]
In the verification, 2.7.1p83 was OK [^ 3]
[^ 2]: So, regarding code replacement, there are various problems with using DateTime, so in the end, in the form of embedding the self-made code created for verification ,,,
[^ 3]: 2.6.3p62 is OK.
Execute the following code with 1.9.2p290, 2.0.0p481, 2.7.1p83, respectively.
test.rb
require 'date'
require 'time'
#Self-made function for control
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.The result of strptime
p DateTime.strptime(str, "%Y,%j,%H:%M:%S %z").strftime("%s").to_i
#Result of self-made function
p ( manu str ).to_i
# Timme.The result of strptime
p Time.strptime(str, "%Y,%j,%H:%M:%S %z").to_i
In 1.9.2 and 2.0.0, Time.strptime does not interpret% j. DateTime.strptime will interpret it.
shell-session:1.9.2p290,2.0.0p481
$ ruby test.rb
1047352911
1047352911
1041391311  # <= 2003/01/01 12:21:51 JST
On the other hand, 2.7.1 also interprets Time.strptime.
shell-session:2.7.1p83
$ ruby test.rb
1047352911
1047352911
1047352911
If there is something like the ruby version of delta, it would be one shot if you read it, but that passion does not spring up ...
Recommended Posts