I am trying to import some data in from a flat file and am getting some odd results. When importing a time that is unattached to a date, why do I get a date inserted into this time as well?
1.9.3-p286 :008 > v.arrival_time = Time.parse("10:10")
=> 2012-11-06 10:10:00 -0400
I'm guessing that there is only a way to keep the date by itself, but no way to keep the time by itself despite the active record column-type :time. Is there a way to keep them separate such as:
1.9.3-p286 :002 > Date.parse("JAN 01 2000")
=> Sat, 01 Jan 2000
DateTime is considered deprecated. It only still exists to be backwards-compatible. As of Ruby 3 (released December 24th, 2020, as is Ruby tradition), DateTime only exists for backwards-compatibility. The date library docs recommend you just use Time instead.
DateTime#now() : now() is a DateTime class method which returns a DateTime object denoting the given calendar date. Return: DateTime object denoting the given calendar date.
You need to convert your string into Date object. For that, use Date#strptime . You can use Date#strftime to convert the Date object into preferred format.
There's this gem tod
, TimeOfDay
which provides functionality like that.
https://github.com/JackC/tod
The Time
object in Ruby uses "Unix Time" to store temporal points as seconds since January 1, 1970 00:00 UTC. Various methods such as strftime
merely change the format of the output, but not how the object is stored internally.
So you have a decision to make: keep your imported data as a Time object, and be mindful of what it actually contains, or import your data as a string but forgo all the lovely, useful features of Time
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With