16

Is there a way to represent a time in ruby without having a Date attached? I am doing a timetracking application and I only need in/out times, there is a separate column for date.

The MySQL TIME data type stores only the time, but in Rails it comes back as Jan 1 2000 + what ever time is there.

Should i just ignore the date part, or is there a way to eliminate it?

loosecannon
  • 7,683
  • 3
  • 32
  • 43

2 Answers2

46

We just store times with no attached dates as minutes since midnight in an integer column (that's Postgres not MySQL but nonetheless). Maybe that approach can work for you too?

Ben Hull
  • 7,524
  • 3
  • 36
  • 56
Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
  • 2
    ah yes, I dont need to store in the db that way , but could be an easy way to compare them. ActiveSupport includes a time.seconds_since_midnight method. – loosecannon Jun 15 '11 at 16:16
  • 1
    exactly what I needed. This guy's a freaking genius. – mraaroncruz Apr 17 '12 at 15:21
  • I would +100 if I could. Damn genius. – David Lesches May 08 '13 at 18:24
  • It's worth mentioning that this may not work for days on which daylight savings is an issue, since they do not have the same number of minutes as other days. – Caleb Hearth Jul 20 '14 at 23:02
  • In my concrete case they were used to represent opening hours. The custom getter just took the minutes and converted them to hours and minutes. – Michael Kohl Jul 21 '14 at 02:38
  • I had a similar situation for storing birthdays without a year. The solution was very similar: store day-of-year in an integer column. Dealing with leap years was just as annoying as dealing with a clock change would be in your situation, but it was still the most practical solution. – Isaac Betesh Jan 19 '15 at 19:48
9

There's no way to eliminate it, because:

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

Just format it like this:

t = Time.now
t.strftime("at %I:%M%p")
sml
  • 2,160
  • 13
  • 12
  • I know i can format it like that, I'm more worried about subtraction and having two different dates. – loosecannon Jun 15 '11 at 15:44
  • 2
    You'll just have to handle it manually using t.hour, t.min, t.sec etc. depending on your accuracy requirements. What happens when the in time is 23:00 and the out time is 01:00? – sml Jun 15 '11 at 15:52
  • if that ever happens they can enter two entries, No body here works those hours, so its not an issue right now. But yeah, alas i was hoping it would just natively support that. – loosecannon Jun 15 '11 at 16:19
  • Yes, Ruby's Time store the seconds, so I am looking for a Class which stores only hours,minutes and seconds (I would call it TimeSpan ) so that i can query: ` WorkLog.where("workduration > ?", TimeSpan.new(8,30,0) ) ` – Klaus Dec 13 '17 at 16:17