conbask
conbask

Reputation: 10061

Parse Date in Ruby

How can I take formatted dates (like 07/11/1990) and convert them into 19900711? a regular expression and some substitution perhaps?

Upvotes: 0

Views: 1843

Answers (3)

barley
barley

Reputation: 4463

require 'date'

DateTime.strptime('07/11/1990', '%m/%d/%Y').strftime('%Y%m%d')

works for me.

Upvotes: 5

Eugene
Eugene

Reputation: 4879

Time class is your friend:

1.9.2p290 :002 > puts Time.parse('07/11/1990').strftime("%Y%d%m")
-->  19900711

You may need to require "time" for this to work though. See string formatted time for more information on the output format.

Upvotes: 4

Spikey21
Spikey21

Reputation: 439

You can use a more efficient way like dateVar.gsub("/",""). Ofcourse replace dateVar for the variable where you'd stored the date in.

Upvotes: 0

Related Questions