Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert MM/DD/YYYY to time in ruby? [duplicate]

I have a date in the format:

MM/DD/YYYY H:MMPM (not sure how to represent the PM)

How do I covert this into a Ruby datetime representation?

like image 697
kidcapital Avatar asked Aug 19 '14 19:08

kidcapital


Video Answer


3 Answers

You should be able to send that string right into Time.parse like so:

2.0.0-p247 :001 > require 'time'
 => true 

Before Ruby 1.9:

2.0.0-p247 :002 > Time.parse("12/1/2014 5:55PM")
 => 2014-12-01 17:55:00 -0500 

After Ruby 1.9

2.0.0-p247 :002 > Time.strptime("12/1/2014 5:55PM","%m/%d/%Y %I:%M%p")
 => 2014-12-01 17:55:00 -0500 
like image 70
Mark Silverberg Avatar answered Oct 28 '22 00:10

Mark Silverberg


Don't use the parse method, or anything based on it, for this.

In the US we use "MM/DD/YYYY" but Ruby, being of a more universal bent, assumes "DD/MM/YYYY", which can cause a lot of failures if the day was > 12. It will also reverse your day and month values.

If today is 'January 2, 2000', parse will get the day/month backwards in a US-based date string:

DateTime.parse('1/2/2000 12:00AM') # => #<DateTime: 2000-02-01T00:00:00+00:00 ((2451576j,0s,0n),+0s,2299161j)>

If the date is 'December 31, 2000', parse will break:

DateTime.parse('12/31/2000 12:00AM') # => 
# ~>  from -:4:in `<main>'
# ~> -:5:in `parse': invalid date (ArgumentError)
# ~>  from -:5:in `<main>'

Ruby assumes day is first:

DateTime.parse('31/12/2000 12:00AM') # => #<DateTime: 2000-12-31T00:00:00+00:00 ((2451910j,0s,0n),+0s,2299161j)>

Trying to work around this situation by sniffing the date string will fail. The only way to ensure you can correctly parse date strings is to know the date format used by user or the software that generated the string, or to always use ISO-based strings that are defined to be a certain format.

Instead, forgo the convenience of anything relying on guessing, and tell Ruby what format to use:

require 'date'

DateTime.strptime('12/31/2000 12:00AM', '%m/%d/%Y %H:%M%p') 
# => #<DateTime: 2000-12-31T00:00:00+00:00 ((2451910j,0s,0n),+0s,2299161j)>
like image 36
the Tin Man Avatar answered Oct 28 '22 01:10

the Tin Man


In rails, you can just call .to_time to a string and it will parse it into a time object

2.1.2 :002 > "12/1/2014 5:55PM".to_time
 => 2014-01-12 17:55:00 -0500 
like image 29
Marc-Alexandre Bérubé Avatar answered Oct 28 '22 01:10

Marc-Alexandre Bérubé