简体   繁体   中英

Ruby - Convert a string to Date

I have a string with the format like

"25/04/14", "12/03/13" (dd/mm/yy)

how to convert it into date format

25-04-2014 , 12-03-2013

in ruby.

Try using strptime :

Date.strptime('25/04/14', '%d/%m/%y')
# => Fri, 25 Apr 2014

if you want date object

date_string = "25/04/14"
date = Date.strptime(date_string, "%d/%m/%y")

if you want 25-04-2014 format string

new_format = date.strftime("%d-%m-%Y")

An easy way out is as under:

require 'date'
Date.strptime('25/04/14' , '%d/%m/%y')
#<Date:2014-04-25>
Date.strptime(s, '%d/%m/%y').strftime("%d-%m-%Y")

console:

2.1.5 :018 > Date.strptime(s, '%d/%m/%y').strftime("%d-%m-%Y")
 => "25-04-2014" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM