Learn and Learn

Learn And Learn - great place for tutorials, references and how-to

Ruby – Get Date using new Date Method – Examples & Explanation

The new method creates a new date object indicating the given calendar date. In this method, BCE years are calculated astronomically. That means the year is 0 before the year 1 and the year before the 0 year is year -1. In this method, the day and the month must be positive of the negative number but not a zero.

Date.new() Method in Ruby

new() method exists in Standard Date Library of Ruby. The purpose of this method is to create the date object indicating the given calendar date.

 

Syntax of the new() Method in Ruby

In date, the syntax of new() method is:

 

Parameter of new() Method in Ruby

The parameter x is any valid date object. In this method, day and the month must be a positive of negative number but not a zero. This parameter is required.Note: If the x parameter is not a date object or zero new() method will return an error.

 

Return Value of Date.new()

Date.new() method will return the date object indicating the given calendar date.

 

Ruby – Create the new Date in new() Date method


Output
2014-11-25T14:35:00+00:00

 

Ruby – Add days in the new() Date method


Output
2014-11-30T14:35:00+00:00

 

Ruby – Convert output in string with new() Date method


Output
“2014-11-25T00:00:00+00:00”

 

Ruby – Set Particular Date Object Example 1


Output
2014-01-01

NOTE: In this method, denoting the year 2014 means the start of the year like 01-01-2014.

 

Ruby – Set Particular Date Object Example 2


Output
2014-11-25

 

Ruby – Get Inverse Date of a month with new() Date method


Output
2014-11-30
2014-11-29
2014-11-28

Note: In the above code -1 means 1 day is subtracted from the depth of a given month.

 

Loading...
LearnAndLearn.com © 2018 - All rights reserved