开发者

Ruby on Rails - Working with times

If in a database (MySQL), I have a datetime column (ex. 1899-12-30 19:00:00), how do I sum 1 day to it?

Following http://corelib.rubyonrails.org/classes/Time.html#M000240

If I want to add 1 day, it actually adds 60*60*24 days (86,400 days)

r=Record.find(:first)
=>Sat, 30 Dec 1899 19:00:00 -0600
r.date + (60*60*24)
=>Fri, 20 Jul 2136 19:00:00 -0600

But if I do this it actually adds 1 day:

t = Time.now
=>Mon Jun 14 10:32:51 -0600 2010
t + (60 * 60 * 24)
=>Tue Jun 15 10:3开发者_如何学C3:21 -0600 2010

I guess it has to do with the format...how do I make this work?


You're actually adding 86,400 seconds (60 seconds * 60 minutes * 24 hours).

ActiveSupport has some built in helper methods for dealing with time:

Time.now + 1.day + 15.hours


In Rails,

its very simple to use times.

 
r = Record.find(:first)

r.created_at + 1.day # this will give you a day to one day ahead ) 

r.created_at + 2.days + 15.hours + 30.minutes + 5.seconds


or use Time.now

Also, if you want take a look at the by_star plugin/gem its makes some querying etc very easy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜