[Ruby] In Time.strptime, %j (the day of the year) is

1 minute read

I needed to maintain someone else’s code, and when I followed the code, I was doing a troublesome task to convert the %j date into UNIX time.

Then, I was disgusted, and when I searched appropriately, “Is there strptime even with ruby?”, bingo!!

a problem occured

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? Can’t you interpret %j?

I couldn’t get an answer even if I googled 1

I tried a lot,

Conclusion

The old ruby Time class (module?) .strptime doesn’t seem to interpret %j 2

In the verification, 2.7.1p83 was OK 3

Verification

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.strptime result
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.strptime result
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 interprets 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 a ruby version of delta, it would be one shot if you read it, but I don’t have that much passion…

  1. It’s special to use %j in the first place… 

  2. With regard to code replacement, there are various problems with using DateTime, and in the end, the self-made code created for verification is embedded. 

  3. You can use 2.6.3p62

Tags:

Updated: