jstar4
jstar4

Reputation: 3

using regex in ruby to change format of date

I'm currently scraping the dates of various events from a website. The date is returned as 2015-04-27T20:00+00:00".

I can use a regular expression to get 2015-04-27 to appear, but am having trouble finding a way to format this date to 27-04-2015, eg dd-mm-yyyy.

Currently I have [/^[^\T]*/].

I have searched other posts but to no avail, any help would be much appreciated.

Upvotes: 0

Views: 632

Answers (2)

Dave Bennett
Dave Bennett

Reputation: 11216

If you did want to do it with regex though you could use this ...

irb(main):019:0> date = '2015-04-27T20:00+00:00'
=> "2015-04-27T20:00+00:00"
irb(main):020:0> date = date.sub(/^(\d+)-(\d+)-(\d+)T.*$/,'\3-\2-\1');
irb(main):021:0* date
=> "27-04-2015"
irb(main):022:0>

Upvotes: 0

Oleksandr Holubenko
Oleksandr Holubenko

Reputation: 4440

You can do it using Date

require 'date'
date = '2015-04-27T20:00+00:00'
puts Date.parse(date).strftime("%d-%m-%Y")

Upvotes: 5

Related Questions