Ruby – Get Valid Date – valid_date? Method of Date Library – Examples & Explanation

The valid_date? method gives the output true if the given calendar date in a code is a valid date otherwise gives false in Ruby language. To get the valid date use valid_date?() method.

valid_date?() Method in Ruby

valid_date?() method exists in Standard Date Library of Ruby. The purpose of this method is to give the valid date of a calendar year from the given code.

 

Syntax of the valid_date?() Method in Ruby

In date, the syntax of valid method is:

Date.valid_date?(x)

Note: If the x parameter is not a valid date or zero the valid_date?() method will return an error.

 

Return Value of valid_date?() Method

valid_date?() method will return true if the given date of a calendar is a valid date or else gives false.

 

Get valid date in Ruby

# import date library
require 'date'
x = Date.valid_date?(2015,9,5)
puts x

Output
true

 

How to set valid_date?() Format in Ruby?

# import date library
require 'date'
def valid_date?(date)
  date_format = '%Y-%m-%d'
  DateTime.strptime(date, date_format)
  true
rescue ArgumentError
  false
end
puts valid_date?('2015-11-30')
puts valid_date?('2015-12-32')
puts valid_date?('2015-2-29')
puts valid_date?('2-29-2015')


Output
true
false
false
false

NOTE: You can set different date formats to get you desired output like (%d %m %Y), (%m %d %Y) and (%Y %d %m).

 

How to validate date in Ruby?

# import date library
require 'date'
def date_valid?(date, date_format)
  Date.parse(date).strftime(date_format) == date
end

puts date_valid?("15 May 2015 Wed", "%d %b %Y %a")
puts date_valid?("15 May 2015 Fri", "%d %b %Y %a")
puts date_valid?("28 Feb 2015 Wed", "%d %b %Y %a")

Output
false
true
false

 

Parse abbreviated date Directly in Ruby

# import date library
require 'date'
abv_date = 'Mar 25'
x = Date.parse abv_date
puts x

Output
{:mon=>3, :mday=>25}

# import date library
require 'date'
abv_date = 'Mar 25'
x = Date.parse abv_date
puts x

Output
2017-03-25

# import date library
require 'date'
abv_date = 'Mar 25'
x = Date.strptime(abv_date, '%b %d').to_s
puts x

Output
“2017-03-25”

 

Parse a date string in Ruby

# import date library
require 'date'
date_string = "20150515"
x = Date.parse(date_string)
puts x

Output
2015-05-15

# import date library
require 'date'
date_string = "201505151325"
x = date = DateTime.parse(date_string,"%Y%m%d")
puts x

Output
2015-05-15T13:25:00+00:00

# import date library
require 'date'
date_string = "201505151325"
x = date = DateTime._parse(date_string,"%Y%m%d")
puts x

Output
{:year=>2015, :mon=>5, :mday=>15, :hour=>13, :min=>25}