From: Clement Ow Date: 2008-04-23T19:08:23+09:00 Subject: Re: Extract date from filenames using regex Jes炭s Gabriel y Gal叩n wrote: > On Wed, Apr 23, 2008 at 11:01 AM, Clement Ow > wrote: >> >> size = (File.size(file))/1024 >> end #if >> >> >>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. Hey Jesus, file_date = DateTime.strptime(match[1], "%d%M%Y") when the above is being put, it will parse the date as eg.28012008 even thought the date is 28032008. So, I tried some trail and error and i used this: file_date = DateTime.strptime(match[1], "%d%m%Y") and bingo, it parses the date correctly and thus being able to run the command to delete. Thanks alot for your time and help! =) Cheers! -- Posted via http://www.ruby-forum.com/.