Ruby: convert string to date

Ruby: convert string to date

Asked on December 26, 2018 in Ruby.
Add Comment


  • 8 Answer(s)

    The Date.strptime() function can be used for convert string to date :

    Date.strptime("{ 2009, 4, 15 }", "{ %Y, %m, %d }")
    
    
    Answered on December 26, 2018.
    Add Comment

    Use this simple one line code in the actual code,

    s = "{ 2009, 4, 15 }"
    d = Date.parse( s.gsub(/, */, '-') )
    
    Answered on December 26, 2018.
    Add Comment

    Have a look at the code below, it may help.

    def parse_date(date)
      Date.parse date.gsub(/[{}\s]/, "").gsub(",", ".")
    end
     
    date = parse_date("{ 2009, 4, 15 }")
    date.day
    #=> 15
    date.month
    #=> 4
    date.year
    #=> 2009
    
    Answered on December 26, 2018.
    Add Comment
    str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
    date = Date.parse str
    => #<Date: 4910837/2,0,2299161>
    puts date
    2010-08-10
    Answered on May 20, 2019.
    Add Comment
    str = "Tue, 10 Aug 2010 01:20:19 +0400"
    puts Date.parse str
    2010-08-10
    puts Date.parse(Time.parse(str).utc.to_s)
    2010-08-09
    Answered on May 20, 2019.
    Add Comment
    str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
    str.to_date
    => Tue, 10 Aug 2010
    Answered on May 20, 2019.
    Add Comment
    Date.strptime(updated, '%a, %d %b %Y %H:%M:%S %Z')
    Answered on May 20, 2019.
    Add Comment
    ext = "get car from repair 2015-02-02 23:00:10"
    dates_from_string = DatesFromString.new
    dates_from_string.find_date(text)
    
    => ["2015-02-02 23:00:10"]
    Answered on May 20, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.