Project

General

Profile

Feature #13259

Kernel#Date

Added by sawa (Tsuyoshi Sawada) almost 3 years ago. Updated almost 3 years ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:79808]

Description

I often see a piece of code like this:

require "date"

begin
  Date.strptime(some_string, some_format)
rescue
  nil
end

Since we now have (https://bugs.ruby-lang.org/issues/12732) Kernel#Integer with a parameter to avoid raising an error in case of an invalid string, I think that having a counterpart of it in Date would be convenient. I propose Kernel#Date, which works like Date.strptime except that it takes an optional keyword argument, and works as follows:

Date("2017/02/02", "%Y/%m/%d", exception: nil) # => #<Date: 2017-02-02 ((2457787j,0s,0n),+0s,2299161j)>
Date("foo", exception: nil) # => nil

History

Updated by shevegen (Robert A. Heiler) almost 3 years ago

I have nothing against it per se but what happens to the Date namespace?

People may be confused when they see Date like the above that used to be part of the
require 'date' call, but now suddenly is part of Kernel.

On a side note though, not specific to the suggestion here, I think a more unified
and simpler way to handle time/date related code in ruby in general would be nice.

Updated by stomar (Marcus Stollsteimer) almost 3 years ago

Note also the ongoing discussion about the future of Date (#13072).

Updated by sawa (Tsuyoshi Sawada) almost 3 years ago

Marcus Stollsteimer wrote:

Note also the ongoing discussion about the future of Date (#13072).

Thanks for the notification. I actually do think there should be a similar thing with Time, and if Date is supposed to become obsolete and be absorbed into Time as the argument suggests, then Kernel#Time would be convenient:

Time("23:55")
Time("foo", exception: nil)

Also available in: Atom PDF