How can I add two weeks to the current Time.now in Ruby? I have a small Sinatra project that uses DataMapper and before saving, I have a field populated with the current time PLUS two weeks, but is not working as needed. Any help is greatly appreciated! I get the following error:
NoMethodError at / undefined method `weeks' for 2:Fixnum
Here is the code for the Model:
class Job include DataMapper::Resource property :id, Serial property :position, String property :location, String property :email, String property :phone, String property :description, Text property :expires_on, Date property :status, Boolean property :created_on, DateTime property :updated_at, DateTime before :save do t = Time.now self.expires_on = t + 2.week self.status = '0' end end
To calculate the number of weeks between two dates, start by counting the number of days between the start and end date. Then, divide that number by 7 days per week.
Add or subtract days from a date Enter your due dates in column A. Enter the number of days to add or subtract in column B. You can enter a negative number to subtract days from your start date, and a positive number to add to your date. In cell C2, enter =A2+B2, and copy down as needed.
To add time, you add the hours together, then you add the minutes together. Because there are only 60 minutes in an hour, you cannot have a time whose minute value is greater than 60. In this case, subtract 60 minutes and add 1 more to the hour.
To find out how many weeks there are between two dates, you can use the DATEDIF function with "D" unit to return the difference in days, and then divide the result by 7.
You don't have such nice helpers in plain Ruby. You can add seconds:
Time.now + (2*7*24*60*60)
But, fortunately, there are many date helper libraries out there (or build your own ;) )
Ruby Date
class has methods to add days and months in addition to seconds in Time. An example:
require 'date' t = DateTime.now puts t # => 2011-05-06T11:42:26+03:00 # Add 14 days puts t + 14 # => 2011-05-20T11:42:26+03:00 # Add 2 months puts t >> 2 # => 2011-07-06T11:42:26+03:00 # And if needed, make Time object out of it (t + 14).to_time # => 2011-05-20 11:42:26 +0300
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With