Search code examples
rubylinux

ArgumentError while parsing date string in Ruby


I'm trying to determine the amount of days from the last .rpm that was installed using ruby, however when I try to format using the Date class, I'm getting that it's an invalid date (ArgumentError) on line 5. I've tried methods of converting it to an integer as well but nothing seems to work. Any thoughts?

require 'date'
require 'time'

tset = `rpm -qa --last | head -1 | rev | cut -d ' ' -f4-6 | rev`
atime = Date.strptime(tset, '%Y-%m-%d')
today = Date.today
btime = Date.strptime(today, '%Y-%m-%d')
daterange = ("btime - atime")
puts daterange

Here is the output of my rpm command

[root@default-centos-67 dev]# rpm -qa --last | head -1 | rev | cut -d ' ' -f4-6 | rev

18 Nov 2016

Solution

  • The result of your rpm command is "18 Nov 2016" and your Date.strptime command is looking for a date with a different format.

    Change:

    atime = Date.strptime(tset, '%Y-%m-%d')
    

    to

    atime = Date.strptime(tset, '%d %b %Y')
    

    I almost always turn to the documentation on strftime to help me with flags for parsing Date and DateTime objects.