Class: Kronic

Inherits:
Object
  • Object
show all
Defined in:
lib/kronic.rb

Class Method Summary collapse

Class Method Details

.format(date, opts = {}) ⇒ Object

Public: Converts a date to a human readable string. If Time.zone is available and set (it is added by active_support and rails by default), Time.zone.today will be used as a reference point, otherwise Date.today will be used.

date - The Date to be converted opts - The Hash options used to customize formatting

:today - The reference point for calculations (default: Date.today)

Returns a relative string (“Today”, “This Monday”) if available, otherwise the full representation of the date (“19 September 2010”).



36
37
38
39
40
41
42
43
44
45
# File 'lib/kronic.rb', line 36

def self.format(date, opts = {})
  case (to_date(date) - to_date(opts[:today] || today)).to_i
    when (2..7)   then "This " + date.strftime("%A")
    when 1        then "Tomorrow"
    when 0        then "Today"
    when -1       then "Yesterday"
    when (-7..-2) then "Last " + date.strftime("%A")
    else               date.strftime("%e %B %Y").strip
  end
end

.parse(string) ⇒ Object

Public: Converts a human readable day (today, yesterday) to a Date. If Time.zone is available and set (added by active_support and rails), Time.zone.today will be used as a reference point, otherwise Date.today will be used.

string - The String to convert to a Date. #to_s is called on the parameter.

Supported formats are: Today, yesterday, tomorrow, last thursday,
this thursday, 14 Sep, Sep 14, 14 June 2010. Parsing is
case-insensitive.

Returns the Date, or nil if the input could not be parsed.



15
16
17
18
19
20
21
22
23
# File 'lib/kronic.rb', line 15

def self.parse(string)
  string = string.to_s.downcase.strip
  now = today

  parse_nearby_days(string, now) ||
    parse_last_or_this_day(string, now) ||
    parse_exact_date(string, now) ||
    parse_iso_8601_date(string)
end