FawzY
FawzY

Reputation: 43

Time datatype in Rails

I created a database using rails with stime attribute (referring to the starting time). Its type is Time. When I added a record with:

stime = "10:10"

it has been added as:

"stime":"2000-0101T10:10:00.000Z"

I only want the time, not the date. I thought it's the difference between Time and DateTime. Could anyone tell me what the problem is?

Upvotes: 3

Views: 5637

Answers (2)

Zoran
Zoran

Reputation: 4226

One way of handling this issue, to exemplify Uzbekjon's third point, is storing the time as seconds since midnight in an integer column:

stime = Time.now
# => 2016-04-13 10:58:13 -0700
seconds = stime.seconds_since_midnight.to_i
# => 39493

You can then retrieve this value and parse it into the time of day when needed:

time = Time.at(seconds).utc
# => 1970-01-01 10:58:13 UTC
result = time.strftime("%I:%M")
# => "10:58"

Hope it helps!

Upvotes: 3

Uzbekjon
Uzbekjon

Reputation: 11823

As the documentation states, it is not.

Time is an abstraction of dates and times. Time is stored internally as the number of seconds with fraction since the Epoch, January 1, 1970 00:00 UTC.

There are several things you can do:

  • Store it as a string and do regex validation.
  • If you are using Postgres and don't mind depending on it, you can use time type. This would allow you do things like: YourModel.where("stime > '13:00:00'").
  • Store the time of the day in seconds since midnight. This will require you to add some helper methods for creating and scopes for querying data. You might find ActiveSupport's extension on numeric values helpful.

Upvotes: 5

Related Questions