Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add two weeks to Time.now?

Tags:

time

ruby

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 
like image 676
Josh Brown Avatar asked May 06 '11 01:05

Josh Brown


People also ask

How do you calculate weeks from now?

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.

How do I add 14 days to a date in Excel?

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.

How do you add time?

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.

How do I calculate weeks from today in Excel?

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.


2 Answers

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 ;) )

like image 120
J-_-L Avatar answered Oct 12 '22 02:10

J-_-L


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 
like image 44
Laas Avatar answered Oct 12 '22 02:10

Laas