Convert a string date format from “17-Nov-2011” to “11/17/11”

后端 未结 3 953
太阳男子
太阳男子 2020-12-31 07:00

I have this code that converts an array of date strings from a format of 17-Nov-2011 to 11/17/11:

def date_convert dates
  months = { \'Jan\' => 1, \'Feb\         


        
相关标签:
3条回答
  • 2020-12-31 07:33

    With Date#strftime you can format a date. Date.strptime allows you a 'reverse' action: Build a date from string.

    When you combine both, you get your result:

    puts Date.strptime('17-Nov-2011', '%d-%b-%Y').strftime('%m/%d/%y')
    

    Each %-Parameters is a part of the date string. You need:

    For parsing the date string:

    • %d: number of the day (17)
    • %b: Month with three letters (Nov)
    • %Y: Year with 4 digits (2011)

    For creating the string:

    • %m: Month (11)
    • %d: number of the day (17)
    • %y: Year with 2 digits (11)
    0 讨论(0)
  • 2020-12-31 07:34

    Use the built-in Time.parse and Time#strftime functions.

    require 'time'
    time = Time.parse("17-Nov-2011")
    time.strftime("%m/%d/%y")
    # => "11/17/11"
    
    0 讨论(0)
  • 2020-12-31 07:50

    Ruby has a pretty robust set of date and time functions, check out the Date class.

    Date.parse("17-Nov-2011").strftime('%m/%d/%y')
    
    0 讨论(0)
提交回复
热议问题