3
\$\begingroup\$

I have two columns representing a date and a time.

{dateproc: '2012-03-23', horproc: '2000-01-01 16:15:23 UTC'}

Both are read as a TimeWithZone by Rails. I need to combine them.

This is what I've done. It works, but it doesn't feel elegant, and it just doesn't seem readable.

date_time_combined = dateproc + horproc.seconds_since_midnight.seconds

Any advice on improving it?

\$\endgroup\$
1
  • \$\begingroup\$ I can't really think of a better way (but I think you can skip the last .seconds call). What you have is pretty straightforward, even if it feels a little "blunt" \$\endgroup\$
    – Flambino
    Commented Dec 16, 2013 at 12:07

2 Answers 2

2
\$\begingroup\$

Nope. That's about as clean as it'll get, though like Flambino said, you can skip the last .seconds call. It's a bit clunky, but that's just how it works out.

\$\endgroup\$
0
\$\begingroup\$

Longer, but a bit more intention-revealing IMHO :

date_utc, hour_utc = dateproc.utc, horproc.utc
date_time_combined = Time.new date_utc.year,
                              date_utc.month,
                              date_utc.day,
                              hour_utc.hour,
                              hour_utc.min,
                              hour_utc.sec
# optionnal
combined_with_time_zone = date_time_combined.in_time_zone

I think it's reasonable to sacrifice conciseness for more obvious code ; especially when dealing with time, which is often hard enough a problem in itself to avoid adding mental gymnastics to the outrage. Your code requires its reader to mentally add and substract time values to understand what's going on, the above does not.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.