On Wed, Apr 23, 2008 at 11:01 AM, Clement Ow
<clement.ow / asia.bnpparibas.com> wrote:
> > Can you post the smallest example that fails? Do you have files with
>  > different date formats?
>  >
>  > Jesus.
>
>
>     delete_date = DateTime.now - delete
>
>     regexp = Regexp.compile(/(\d\d)(\d\d)(\d\d\d\d)/)
>
>
>
>     fileData = Struct.new(:name, :size)
>     deleted_files = []
>
>     folders.each do |folder|
>       Dir.glob(folder+"/*") do |file|
>       puts match = regexp.match(File.basename(file))
>         if match
>           file_date = DateTime.strptime(match[1] , fmt='%d%M%Y')
>
>           size = (File.size(file))/1024
>           if delete_date > file_date
>             deleted_files << fileData.new(file,size)
>             FileUtils.rm_r file
>             if File.exist?(file)==false
>               puts "Files/Folders deleted: #{file} size: #{size} KB"
>               end #if
>             end #if
>         end #if
>       end #do
>     end #each
>   end #if
>  end #delFiles
>
>  >>it'll show this error:
>
> c:/ruby/lib/ruby/1.8/date.rb:1536:in `new_by_frags': invalid date
>  (ArgumentError
>  )
>         from c:/ruby/lib/ruby/1.8/date.rb:1563:in `strptime'
>
>         from testing.conf.rb:166:in `delFiles'
>
>  >>I do have files with different date formats, but the format yyyymmdd works when i use DateTime.parse maybe
> because DateTime accepts this format?

Yes, that's exactly the issue.

> however if i use strptime it also cant work. Any help will be greatly appreciated =)

If you have files with different formats, you will have to know which
format each file is, because DateTime.parse is expecting yyyymmdd,
while strptime is expecting whatever format you pass it, but only one
format. If the dates are current dates, and are only these two formats
(yyyymmdd or ddmmyyyy) I think this is safe:

regexp = /(\d{8})/
match = regexp.match(file_name)
file_date = nil
begin
  file_date = DateTime.parse(match[1])
rescue ArgumentError
  file_date = DateTime.strptime(match[1], "%d%M%Y")
end

However, if you have arbitrary dates, this can lead to unexpected
results. For example:

19011902

will result in 1901-19-02 while maybe you meant 19-01-1902.
Also, I think the above is safe because the century (20xx for the
year) is not a valid month, but there might be some corner case I
haven't realized.

Jesus.