Thursday, October 21, 2010

One hour from now...

So, I'm a long-time Java guy, wading into Ruby/Rails and really liking it so far. I know most of you who have made the transition are already aware of how much nicer many things in RoR-land are, but I thought I'd start just collecting a series of posts on my own personal findings. Just 'cause.

Case in point, this morning I was writing a unit test in Java, and needed to use two dates in my test code, one that was further in the future than the other. In Java, this looks something like this:

Date now = new Date();
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
Date oneHourFromNow = calendar.getTime();

I know I don't need to explicitly set the calendar to 'now', however, I use the 'now' reference in the tests, so it seemed to be slightly more correct and explicit to do so. Further, the only reason for this setup code is to use the now and oneHourFromNow references in my tests.

In Rails, I would simply reference:

when I wanted to get the current time, and then use the nice time-related functions that Rails adds: + 1.hour

when I needed a time that was in the future. If I wanted the exact same semantics as the Java code, I suppose I could do this:

now =
one_hour_from_now = + 1.hour

but that doesn't seem to add much in the way of comprehensibility, so I'd likely skip that altogether.

So, in reality, what would take me five lines of code in Java, essentially takes zero in Rails, which, as I calculate things, is infinitely better.


Anonymous said...

Does that handle if the hour addition extends across a spring ahead / fall back time change? If so, that's pretty sweet!

Carl Schmidt said...

Yup, sure does. It's easy to try this for yourself from the Rails console. Here in Canada our next change is on November 7th at 2:00am. So...

>> time = Time.parse '2010-11-7 01:00'
=> Sun Nov 07 01:00:00 -0700 2010
>> time + 1.hour
=> Sun Nov 07 01:00:00 -0800 2010

Stephan Wehner said...

1.hour.from_now is even shorter and easier to read.

Carl Schmidt said...

Thanks for that Stephan!

for ict 99 said...
This comment has been removed by a blog administrator.
Robert said...

That is really nice to hear. thank you for the update and good luck. wofs

Tangki Fiber said...

You managed to hit the nail upon the top and also defined out the whole thing without having side effect , people could take a signal. Will likely be back to get more. Thanks
Tangki Panel

Anna Schafer said...

You’ve got some interesting points in this article. I would have never considered any of these if I didn’t come across this. Thanks!. UAE Embassy attestation