Reputation: 3538
I would like to split strings like "12:30am"
and "6:55pm"
and separate the am
/pm
from the time. Is there a way to use String#split
to do that?
Alternatively, is there a better way to turn that string in to a Time
object?
Upvotes: 0
Views: 60
Reputation: 168259
You don't need to do anything special. All you need to do is use the "time"
library.
require "time"
Time.parse "12:30am"
# => 2014-05-04 00:30:00 +0900
Time.parse "6:55pm"
# => 2014-05-04 18:55:00 +0900
Upvotes: 2
Reputation: 507
You could do something like Time.parse("12:00am".gsub(/am|pm/i, ""))
to get any of those endings off. The gsub will remove those characters based on the /am|pm/i
regex. The pipe being an or and the i makes it case insensitive. Check out rubular for help using gsub or any regex in ruby.
As for better time methods, I would recommend trying the gem chronic for more flexible, expressive time methods. Here are some examples from its documentation.
require 'chronic'
Time.now #=> Sun Aug 27 23:18:25 PDT 2006
Chronic.parse('tomorrow')
#=> Mon Aug 28 12:00:00 PDT 2006
Chronic.parse('monday', :context => :past)
#=> Mon Aug 21 12:00:00 PDT 2006
Chronic.parse('this tuesday 5:00')
#=> Tue Aug 29 17:00:00 PDT 2006
Chronic.parse('this tuesday 5:00', :ambiguous_time_range => :none)
#=> Tue Aug 29 05:00:00 PDT 2006
Chronic.parse('may 27th', :now => Time.local(2000, 1, 1))
#=> Sat May 27 12:00:00 PDT 2000
Chronic.parse('may 27th', :guess => false)
#=> Sun May 27 00:00:00 PDT 2007..Mon May 28 00:00:00 PDT 2007
Chronic.parse('6/4/2012', :endian_precedence => :little)
#=> Fri Apr 06 00:00:00 PDT 2012
Chronic.parse('INVALID DATE')
#=> nil
Upvotes: 1