Unlike next month method, the prev_month
method is used to get one month less than the month given in a code. For example, if in your code, you have entered the fourth month of the year 2016 and with the help of prev_month
method, you will find the third month of that year. You can also get the desired month less than the month given in a code with the help of this method of Ruby.
Syntax of prev_month
Method in Ruby
Date.new(x).prev_month
Parameter of prev_month
Method in Ruby
x
– where x
is any valid date object such as 2016, 4, 10. This parameter is required.Error Handling of prev_month
Method in Ruby
If the
x
parameter is not a valid date object the prev_month
method will return an error and it could be due to the wrong format of the date in a code or the use of zero.Return Value of prev_month
Method in Ruby
prev_month
method will return one month less than the month given in a code. You can also get desired month by using this method of Ruby.Ruby prev_month
Method Example
# import date library require 'date' x = Date.new(2016,4,10).prev_month puts x
Output:
2016,3,10
Ruby Different Methods of prev_month
# import date library require 'date' x = DateTime.new(2014,6,10, 11, 20, 15).prev_month x = DateTime.new(2014,4,5, 11, 20, 15).prev_month(2) puts x
Output:
2014-05-10T11:20:15+00:00
2014-04-10T11:20:15+00:00
How to Print Previous Month from Current Month in Ruby?
# import date library require 'date' # you can get desired month which would be less than the month in the code x = Date.new(2016,10,25).prev_month(2) x = Date.new(2016,10,25).prev_month(6) puts x
Output:
2016-08-25
2016-04-25