Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an add_days in ruby datetime?

Tags:

ruby

In C#, There is a method AddDays([number of days]) in DateTime class.

Is there any kind of method like this in ruby?

like image 934
Jirapong Avatar asked Aug 31 '09 08:08

Jirapong


People also ask

How to add day to Date in Ruby?

require 'date' puts "Enter a start date: (MM/DD/YYYY)"date = gets. chomp start_date = Date. strptime(date, "%D") puts "How many days was your Trip?[Ex.

How do you parse time in Ruby?

Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.


2 Answers

The Date class provides a + operator that does just that.

>> d = Date.today => #<Date: 4910149/2,0,2299161> >> d.to_s => "2009-08-31" >> (d+3).to_s => "2009-09-03" >>  
like image 123
Steve Weet Avatar answered Oct 01 '22 21:10

Steve Weet


In Rails there are very useful methods of Fixnum class for this (here n is Fixnum. For example: 1,2,3.... ):

Date.today + n.seconds # you can use 1.second Date.today + n.minutes # you can use 1.minute Date.today + n.hours # you can use 1.hour Date.today + n.days # you can use 1.day Date.today + n.weeks # you can use 1.week Date.today + n.months # you can use 1.month Date.today + n.years # you can use 1.year 

These are convenient for Time class too.

PS: require Active Support Core Extensions to use these in Ruby

require 'active_support/core_ext' 
like image 42
Jiemurat Avatar answered Oct 01 '22 21:10

Jiemurat