How to Truncate a Ruby Time Down to the Second, Minute, Hour, or Day

Sometimes you have a Time or DateTime object in Ruby and you want to zero out the milliseconds, seconds, minutes, or hours. And if you’re zeroing out a larger element like minutes, you’d like it to automatically zero out the smaller elements like seconds and milliseconds too.

It turns out ActiveSupport extends Time and DateTime with a method to do this: change. As the documentation says, “The time options (hour, minute, sec, usec) reset cascadingly, so if only the hour is passed, then minute, sec, and usec is set to 0. If the hour and minute is passed, then sec and usec is set to 0.”

To truncate a Time to the second, minute, hour, or day:

  time.change(:usec => 0) # zero out milliseconds
  time.change(:sec => 0)  # zero out seconds, milliseconds
  time.change(:min => 0)  # zero out mins, secs, & usecs
  time.change(:hour => 0) # zero out hrs, mins, secs, usecs

To truncate a DateTime to the minute, hour, or day:

  datetime.change(:sec => 0)  # zero out seconds
  datetime.change(:min => 0)  # zero out mins and secs
  datetime.change(:hour => 0) # zero out hrs, mins, secs

Sensibly, changing the year, month, or day of a DateTime does not reset the lower elements to zero.

ActiveSupport also adds the change method to Date, but since the only elements are year, month, and day, it never zeroes out the smaller elements when you set a larger element.

Action-Oriented Programming and The History of HTML

I just read a fascinating history of HTML, up to HTML5 by Mark Pilgrim.

One sentence keeps repeating in this essay:

“The proposal was never implemented.”

Pilgrim’s point is that shipping software wins over specs and ideas. Or in his words, “The ones that win are the ones that ship.” (Although he points out that shipping code is necessary but not sufficient for success.) A number of times HTML was “retro-specced” to match what had already been implemented.

I like that. In 2006 I coined the term “Action-Oriented Programming” on a Joel on Software discussion board:

Regarding motivation to get started implementing a product idea once you have one:

Whatever you do, do something.

Us programmers, we tend to overanalyze things. Lots of up-front design, trying to decide if it’s the right thing to do, not sure if we have enough education yet, etc. But from what I’ve read about successful entrepreneurs, they are DOERS. They’re Action-Oriented.

So I’m inventing a new term:

Action-Oriented Programming: writing the damn program instead of thinking about writing it.

The HTML spec evolved through Action-Oriented Programming. Read the History of HTML essay and you’ll see why.

P.S. Hey, I know I didn’t invent the idea of favoring working code over detailed specs. But I like the name I gave it. 🙂 I’m pleased to see that Action-Oriented Programming has become popular with the rise of agile techniques and “Getting Real.”