2

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!

1 Answers1

4

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" 
Konrad Reiche
  • 27,743
  • 15
  • 106
  • 143
  • Thanks platzhirsch! I tested this out on the console and it assumes today's date. Is there a way to have it only save the time data independent of any date? –  Aug 11 '13 at 18:26
  • I am recording these times as the beginning/end of weekly events, and later down the road want to be able to compare using the time value to see which one starts earlier/later. If I have a date associated with the time my comparisons will not be accurate. –  Aug 11 '13 at 18:29
  • @ChristophePrakash In this case you could convert between `Time` and `DateTime` format, see http://stackoverflow.com/questions/279769/convert-to-from-datetime-and-time-in-ruby – Konrad Reiche Aug 11 '13 at 18:31