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

work_started_at.to_s("%Y-%m-%d")

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
else
  # work_started_at is nil
end
2 Likes

Thank you,
Both worked.