Date string error

10,150

Solution 1

The code:

def released_on=date
  super Date.strptime(date, '%m/%d/%Y')
end

Uses the strptime (string-parse-time) function of the Date class. It expects two strings, one representing the actual date, and one with a string formatter.

All you need to do in order to get things working is to change:

song.released_on = Date.new(2013,10,10) # Wrong, not a string!
song.released_on = '10/10/2013' # Correct!

You could also change the function to also accept a date:

def released_on=date
  parsed_date = case date
    when String then Date.strptime(date, '%m/%d/%Y')
    when Date then date
    else raise "Unable to parse date, must be Date or String of format '%m/%d/%Y'"
  end
  super parsed_date
end

Solution 2

You pass a Date instance to Date::strptime:

date = Date.new(2013,10,10)
Date.strptime(date, '%m/%d/%Y')  #=> TypeError: no implicit conversion of Date into String

Instead you have to pass a String (using the correct format):

date = "10/10/2013"
Date.strptime(date, '%m/%d/%Y')  #=> Thu, 10 Oct 2013
Share:
10,150
Frederik
Author by

Frederik

Updated on June 19, 2022

Comments

  • Frederik
    Frederik almost 2 years

    When I try to add my date via IRB in terminal:

    song.released_on = Date.new(2013,10,10)
    

    it says there is following error TypeError: no implicit conversion of Date into String

    in this code:

    def released_on=date
      super Date.strptime(date, '%m/%d/%Y')
    end 
    

    I've tried for several hours know and cant find the issue. Was wondering someone could help out?