user2993456
user2993456

Reputation:

How to make Time.now less precise?

I simply want to return a less precise, truncated version of Time.now.

When I run Time.now I get a very precise object 2014-10-02 14:49:47 -0400tim. I only want YYYY-MM-DD HH:MM:MM.

How can I (temporarily) cast the precision of a Time.now return object?

Upvotes: 0

Views: 94

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110725

You could create a new Time object that is the original time rounded to the nearest minute:

require 'time'

t = Time.now
  #=> 2014-10-02 12:40:22 -0700
new_time = t + (t.sec >= 30 ? 60-t.sec : -t.sec)
  #=> 2014-10-02 12:40:00 -0700

t += 30
  #=> 2014-10-02 12:40:52 -0700
new_time = t + (t.sec >= 30 ? 60-t.sec : -t.sec)
  #=> 2014-10-02 12:41:00 -0700

Upvotes: 0

Grice
Grice

Reputation: 1375

strftime() allows you to provide a format string for your time object. A list of format flags can be found in the documentation

Example from Docs:

t = Time.new(2007,11,19,8,37,48,"-06:00") #=> 2007-11-19 08:37:48 -0600
t.strftime("Printed on %m/%d/%Y")   #=> "Printed on 11/19/2007"
t.strftime("at %I:%M%p")            #=> "at 08:37AM"

Your Example:

t.strftime("%Y-%m-%d %T")    #=> YYYY-MM-DD HH:MM:MM.

Upvotes: 1

Related Questions