Posts for Tag: time

Date and time in ruby

Time.now will give you the current date (and time), like so:

Time.now 2012-11-22 22:35:01 +0000

You can also request all the date parts individually:

Time.now.hour 22 Time.now.min 35 Time.now.sec 01 Time.now.day 22 Time.now.month 11 Time.now.year 2012

Cool (and easy), right? If you want to change a date, you can add seconds to it:

t = Time.now 2012-11-22 22:35:01 +0000 t2 = t + 10 # 10 Seconds 2012-11-22 22:35:11 +0000 t3 = t + 10*60 # 10 minutes 2012-11-22 22:45:01 +0000 t4 = t + 10*60*60 # 10 hours 2012-11-23 08:35:01 +0000

If you happen to be developing a Ruby on Rails application then it gets even easier:

t = Time.now 2012-11-22 22:35:01 +0000 t2 = t + 1.hour 2012-11-22 23:35:01 +0000

That's right, in Rails numerals get some extra methods injected into them, like hour, hours, minute, minutes, second, seconds, day, days, and so on... And people still ask me why i love Ruby (and Rails)... :)