codecalypso
codecalypso

Reputation: 71

Change date format in ruby

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

Answers (4)

dimid
dimid

Reputation: 7631

Without regex, but will solve your problem:

"29-07-2015".split('-').reverse.join('-')

Upvotes: 0

Charles
Charles

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

user4227915
user4227915

Reputation:

With regex, something like that:

(\d{2})-(\d{2})-(\d{4})

Regex live here.

Upvotes: 0

tadman
tadman

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

Related Questions