Search code examples
rubystringstrftime

How to convert Strftime into string in Ruby?


I want to parse this strftime into a string, then just isolate the day variable.

 '2015-04-15T11:15:34'

I know in python, you could do something like:

 datetime.strptime(element, "%Y-%m-%dT%H:%M:%S")

after importing something like:

 from datetime import datetime
 from datetime import timedelta

Is there a module or function in Ruby that can do this efficiently?


Solution

  • Yes. It's also called strptime. http://ruby-doc.org/stdlib-2.1.1/libdoc/date/rdoc/DateTime.html#method-c-strptime

    Parses the given representation of date and time with the given template, and creates a date object. strptime does not support specification of flags and width unlike strftime.

    DateTime.strptime('2001-02-03T04:05:06+07:00', '%Y-%m-%dT%H:%M:%S%z') #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>

    After including the required date library, you could then call #day on the resulting DateTime object to get the day. eg.

    irb(main):016:0> require 'date'
    => true
    irb(main):017:0> date = DateTime.strptime('2015-04-15T11:15:34', "%Y-%m-%dT%H:%M:%S")
    => #<DateTime: 2015-04-15T11:15:34+00:00 ((2457128j,40534s,0n),+0s,2299161j)>
    irb(main):018:0> date.day
    => 15