The Crystal Programming Language Forum

Is there some method for time format without nil error?

Hello, I am a newbie in crystal.
I have a trouble to format time to string in render,
I select the time field from db, we can say it work_started_at,
and it should be (Time | Nil)
then when I type


The compiler said the error:

no overload matches ‘Nil#to_s’ with type String
Overloads are:

  • Nil#to_s(io : IO)
  • Nil#to_s()
  • Object#to_s(io : IO)
  • Object#to_s()

How should I do with it?

You would need to make sure the value returned from the database is not nil first. Most ORMs have a method to get the value as not nil when you know its not nil, for example in Granite model.work_started_at!, notice the !.

Another option of that isn’t a feature is to do like

if start = work_started_at
  # start is known to be not nil here
  # Then could do start.to_s
  # work_started_at is nil

Thank you,
Both worked.