mohangraj
mohangraj

Reputation: 11034

Date validation in Ruby

How to check if the date is valid date in ruby. Many of the methods are check only the range. But, I need to check the date with day of week to check whether the date is valid or not. For Ex:

    20 Jul 2016 Wed --> Valid
    20 Jul 2016 Mon --> Not-Valid

How to do this in ruby ?

Upvotes: 1

Views: 2484

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

require 'date'

dates = ['20 Jul 2016 Wed', '20 Jul 2016 Mon']

dates.select do |s|
  d = Date.strptime(s[0,11], "%d %b %Y") rescue nil
  d.nil? ? false : (Date::ABBR_DAYNAMES[d.wday] == s[-3,3])
end
  #=> ["20 Jul 2016 Wed"]

This reads, "select strings 'dd mmm yyyy' that represent valid dates and whose day-of-week matches the day-of-week given by the last three characters of the string".

Upvotes: 1

retgoat
retgoat

Reputation: 2464

I'm not pretend on the best solution ever, but this should work.

def valid_date?(date)
  Date.parse(date).strftime("%d %b %Y %a") == date
end

[55] pry(main)> valid_date?("20 Jul 2016 Wed")
=> true
[56] pry(main)> valid_date?("20 Jul 2016 Mon")
=> false
[57] pry(main)>

If you have many formats you may pass format as a second argument

def valid_date?(date, fmt)
  Date.parse(date).strftime(fmt) == date
end

=> :valid_date?
[59] pry(main)> valid_date?("20 Jul 2016 Wed", "%d %b %Y %a")
=> true

Hope this will help.

UPDATE

As I mentioned in comment that method name overlaps with existing method valid_date?

So, you may just rename the custom method

def date_valid?(date, fmt)
  Date.parse(date).strftime(fmt) == date
end

[2] pry(main)> date_valid?("20 Jul 2016 Wed", "%d %b %Y %a")
=> true

Upvotes: 2

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Just out of curiosity:

dates = ['20 Jul 2016 Wed', '20 Jul 2016 Mon']
dates.map do |date|
  Date.parse(date).public_send(
    Date.instance_methods.detect do |m|
      m.to_s =~ /\A#{date[-3..-1].downcase}.*day\?\z/
    end)
end
#⇒ [ true, false ]

Upvotes: 1

Related Questions