首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RubyZip设置文件时间戳

RubyZip设置文件时间戳
EN

Stack Overflow用户
提问于 2018-05-11 03:39:36
回答 1查看 176关注 0票数 0

我整天都在苦苦思索这件事,也许你能帮上忙?我正在用RubyZip压缩文件,我需要将文件创建/更新/修改的时间设置为时区中的特定时间(这取决于我在@time_zone变量中的客户端时区)。

我知道这很可能是超级错误的,我从RubyZip测试文件中提取了神奇的字符串'UT\x5\0\x3\250$\r@Ux\0\0',但我不知道这是什么。LOL。然而,我现在已经让它在我的PC上工作了。它确实会压缩文件,并根据指定的时区为其设置正确的时间戳。

但是-它不能在应用服务器上工作,因为操作系统时区在UTC时区。它会为不匹配的文件生成其他时间。

下面是我让它走了多远:

代码语言:javascript
复制
def save_to_zip(file_path)
  Zip::OutputStream.open(file_path) do |out|
    @sheets.each do |csv|
      name = csv.name
      extra = time_for_zip
      out.put_next_entry("#{name}.#{@file_extension}", nil, extra)
      tmpfile = csv.tmpfile
      tmpfile.close
      source = File.open(tmpfile.path, 'r')
      source.each do |line|
        out.write(line)
      end
    end
  end
end

def time_for_zip
  return nil if @time_zone.blank?

  timestamp = Zip::ExtraField.new('UT\x5\0\x3\250$\r@Ux\0\0')
  localtime_str = Time.now.in_time_zone(@time_zone).strftime("%Y-%m-%dT%H:%M:%S")
  dos_time_in_store_tz = ::Zip::DOSTime.parse(localtime_str)

  timestamp['UniversalTime'].ctime = dos_time_in_store_tz
  timestamp['UniversalTime'].atime = dos_time_in_store_tz
  timestamp['UniversalTime'].mtime = dos_time_in_store_tz

  timestamp
end

你能告诉我怎样才能在zip文件中正确设置文件时间吗?

真的很感激。

Maris

EN

回答 1

Stack Overflow用户

发布于 2018-05-11 14:15:52

解决方法如下:

代码语言:javascript
复制
    def save_to_zip(file_path)
  Zip::OutputStream.open(file_path) do |out|
    @sheets.each do |csv|
      name = csv.name
      tmpfile = csv.tmpfile
      tmpfile.close
      source = File.open(tmpfile.path, 'r')
      zip_entry = Zip::Entry.new(out, "#{name}.#{@file_extension}", nil, nil, nil, nil, nil, nil, time_for_zip(source.ctime))
      out.put_next_entry(zip_entry)
      source.each do |line|
        out.write(line)
      end
    end
  end
end

def time_for_zip(file_time)
  return Zip::DOSTime.at(file_time) if @time_zone.blank?

  Zip::DOSTime.parse(file_time.utc.in_time_zone(@time_zone).strftime("%Y-%m-%d %H:%M:%S"))
end

向这个帖子致敬:https://github.com/rubyzip/rubyzip/pull/40

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50280357

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档