Search code examples
crystal-lang

How do I parse a String to Time in Crystal Lang?


I have a String in MM-DD-YYYY format such as: 04-08-2022.

I want to parse that to a Time type.

How do I do that in Crystal?


Solution

  • Crystal has a Time.parse (documentation link) method which can be used in this scenario.

    The method receives a String argument to parse along with a String pattern argument and the requested Location of the time. Here is the method signature below.

    def self.parse(time : String, pattern : String, location : Location) : Time
    

    For your example, we could use the formatter to provide our custom format as %m-%d-%Y, where %m means month MM format, %d means day DD format, and %Y means YYYY format. Finally we use the local Location of the script being run.

    For example:

    time = Time.parse("04-08-2022", "%m-%d-%Y", Time::Location.local)