Domanda

How would I get the age of a file in days in Ruby?

NOTE that I need a way to accurately get the age of a given file; this means that leap years need to be taken into account.

I need this for a program that removes files after they reach a certain age in days, such as files that are 20 days or older.

And by age, I mean the last access time of a given file, so if a file hasn't been accessed in the past 20 days or more, it gets deleted.

In Perl, I know that you can use date::calc to calculate a date in terms of days since 1 AD, and I used to have a Common-Lisp program that used the Common-Lisp implementation of date::calc, but I don't have that anymore, so I've been looking for an alternative and Ruby seems to have the required capability.

È stato utile?

Soluzione

path = '/path/to/file'    
(Time.now - File.stat(path).mtime).to_i / 86400.0
#=> 1.001232

Here is the implementation of my above comment, it returns a floating point number expressing the number of days passed.

Altri suggerimenti

I know it is an old question, but I needed the same and came up with this solution that might be helpful for others.

As the difference is in days, there is not need to directly deal with seconds.

require 'date'
age_in_days = (Date.today - File.mtime(path).to_date).to_i
if age_in_days > 20
    # delete logs
end

If using Rails, you can take advantage of ActiveSupport:

if File.mtime(path) < 20.days.ago
  # delete logs
end

If you aren't using Rails, Eduardo's solution above would be my pick.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top