Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you have a time without a date in rails?

Tags:

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 
like image 648
ovatsug25 Avatar asked Nov 06 '12 18:11

ovatsug25


People also ask

Is DateTime deprecated Ruby?

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.

What does DateTime now return in Ruby?

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.

How do I change the date format in Ruby on Rails?

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.


2 Answers

There's this gem tod, TimeOfDay which provides functionality like that.

https://github.com/JackC/tod

like image 44
Timo Avatar answered Oct 16 '22 15:10

Timo


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.

like image 58
Dmitri Avatar answered Oct 16 '22 16:10

Dmitri