Reputation: 71
my date = "29-07-2015"
what I want: "2015-07-29"
This works in irb but not my ruby file:
date.gsub(/(\d{2})-(\d{2})-(\d{4})/, '\3-\2-\1')
Is there an alternative way to do this?
Upvotes: 0
Views: 365
Reputation: 7631
Without regex, but will solve your problem:
"29-07-2015".split('-').reverse.join('-')
Upvotes: 0
Reputation: 1396
All you need to do is my_date.reverse!
. All you want is to flip that date, and it is a string. Strings can be reversed.
Upvotes: 0
Reputation: 211590
Just parse and rewrite:
require 'date'
d = Date.strptime('29-07-2015', '%d-%m-%Y')
d.strftime('%Y-%m-%d')
# => "2015-07-29"
The strptime
function and strftime
function take the same formatting options, so they can undo what the other produces.
Upvotes: 6