1

I'm trying to parse some dates with bad formatting in Ruby. I decided to hinge part of the method on the presence of am or pm, so I've split the string there.

def bad_date(date)
  if date.match(/m\d/i)
    date_time = date.split('m', 2).reverse
    time = date_time.include?('m')
    date = date_time - time
  else
    date
  end
end

It split in the right place and reverse the array it's all good, but it takes the m with it. How can I replace it? Or how can I avoid that entirely?

Essentially I'm trying to convert some dates like this:

dates
=> ["0900am06/13/2015", "0900 am06/13/2015", "0900am 06/13/2015", "0900 am 06/13/2015"]

Into this:

2015-06-13 09:00 AM

With an acceptable margin of error.

1
  • 1
    This SO answer has a solution for keeping the delimiter upon splitting a string. It can be repurposed to keep the m. Hope it helps! Commented May 28, 2015 at 9:49

2 Answers 2

3

You can take a help of strptime and strftime methods both :

require 'date'

d = Date.strptime("0900am06/13/2015", "%H%M%p%m/%d/%Y")
# => #<Date: 2015-06-13 ((2457187j,0s,0n),+0s,2299161j)>
d.strftime("%Y-%m-%d %H:%M %P")
# => "2015-06-13 00:00 am"
d.strftime("%Y-%m-%d %H:%M %p")
# => "2015-06-13 00:00 AM"

Here is a method:

require 'date'

def bad_date(date)
  DateTime.strptime(date.tr(" ",''), "%H%M%p%m/%d/%Y").strftime("%Y-%m-%d %H:%M %p")
end

dates = ["0900am06/13/2015", "0900 am06/13/2015", "0900am 06/13/2015"]
dates.map { |d| bad_date d }
# => ["2015-06-13 09:00 AM", "2015-06-13 09:00 AM", "2015-06-13 09:00 AM"]
Sign up to request clarification or add additional context in comments.

1 Comment

d = Date.strptime("0900am06/13/2015".gsub(/ /,''), "%H%M%p%m/%d/%Y")
2
2.1.0 :085 > date = "0900am 06/13/2015"
 => "0900am 06/13/2015" 
2.1.0 :086 > date.gsub!(" ","")
 => "0900am06/13/2015" 
2.1.0 :087 > Date.strptime(date, "%H%M%p%m/%d/%Y")
 => Sat, 13 Jun 2015 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.