user2469227
user2469227

Reputation:

Parsing string "10:00AM" to DateTime Type?

I'm reading strings off of html but want to store them in a database as a DateTime field type. What is a simple way to do this while correctly preserving AM/PM data?

Thanks!

Upvotes: 2

Views: 1630

Answers (1)

Konrad Reiche
Konrad Reiche

Reputation: 29503

Your access layer for the database should support the Ruby DateTime type, hence you can parse it as follows:

require 'date'

DateTime.parse("10:00AM") 
# => #<DateTime: 2013-08-11T10:00:00+00:00 ((2456516j,36000s,0n),+0s,2299161j)> 

The whole meridiem notation (AM/PM) is at the presentation level. Your database will store it in its DateTime structure and everytime your retrieve it back into Rails, you can get your presentation by using strftime

your_date.strftime("%I:%M%p") 
=> "10:00AM" 

Upvotes: 4

Related Questions