Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date string error [closed]

Tags:

string

date

ruby

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?

like image 973
Frederik Avatar asked Aug 01 '26 03:08

Frederik


1 Answers

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
like image 135
hirolau Avatar answered Aug 03 '26 18:08

hirolau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!