LoginSignup
3
1

More than 3 years have passed since last update.

rubyzip でZIPを作るときに秒がズレないように日時を入れる方法

Last updated at Posted at 2020-11-29

Zip::Entry.new の後ろの方に日時を渡すのではなく、インスタンスの time= に渡すと秒がズレないようです

entry = Zip::Entry.new(zos, "foo1.txt", nil, nil, nil, nil, nil, nil, dos_time)

entry = Zip::Entry.new(zos, "foo2.txt")
entry.time = dos_time

下のが検証したコードです

require "zip"
require "zip/version"
require "time"

Zip::VERSION                    # => "2.3.0"

created_at = Time.parse("2020-01-01 00:00:05") # => 2020-01-01 00:00:05 +0900
dos_time = Zip::DOSTime.from_time(created_at)  # => 2020-01-01 00:00:05 +0900

io = Zip::OutputStream.write_buffer do |zos|
  # ズレる方法
  entry = Zip::Entry.new(zos, "foo1.txt", nil, nil, nil, nil, nil, nil, dos_time)
  zos.put_next_entry(entry)

  # ズレない方法
  entry = Zip::Entry.new(zos, "foo2.txt")
  entry.time = dos_time
  zos.put_next_entry(entry)
end
File.write("foo.zip", io.string)
`unzip -o foo.zip`
puts `ls -go --full-time foo*.txt`
# >> -rw-r--r-- 1 0 2020-01-01 00:00:04.000000000 +0900 foo1.txt
# >> -rw-r--r-- 1 0 2020-01-01 00:00:05.000000000 +0900 foo2.txt

参考

rubyzipを使ってファイル圧縮する際に任意の変更日付をいれてテストしてみたら展開ファイルが1秒ズレてハマったという話。
https://qiita.com/kitaindia/items/894a3a600e0892dc0197

3
1
0

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
3
1