Ruby / Dates and times

From WhyNotWiki

Jump to: navigation, search

Dates, Times, and Datetimes, oh my!

Contents

[edit] How do you create a new Date/Time from (year, month, day) values?

Time (with local timezone) Time.local(year, month, day, ...) / Time.mktime(...) Sat Jul 01 00:00:00 -0700 2006
(with UTC timezone) Time.utc(year, month, day) Sat Jul 01 00:00:00 UTC 2006
Date (no timezone information) Date.new(year, month, day) "2006-07-01"
DateTime (no timezone information?) DateTime.civil(year, month, day) "2006-07-01T00:00:00Z"

Confusingly, the Rdoc (at http://www.ruby-doc.org/core/classes/Date.html#M000480) shows the documentation for new0 where it should show the documentation for new! That is, you can't even find the documentation for new() in the standard Rdoc!!

Find it here instead: http://www.rubycentral.com/pickaxe/lib_standard.html#Date.new


[edit] How do I turn a string into a Date?

(how do I "parse" a string that contains a date)

irb -> require 'date'

irb -> Date.strptime('2007-04-04')
    => #<Date: 4908389/2,0,2299161>

irb -> Date.parse('2007-04-04')
    => #<Date: 4908389/2,0,2299161>

irb -> Time.parse('2007-04-04')
    => Wed Apr 04 00:00:00 -0700 2007

irb -> DateTime.parse('2007-04-04')
    => #<DateTime: 4908389/2,0,2299161>


[edit] What's the difference between Date and Time and DateTime?

To do: make a table that shows which methods are available in each

/usr/lib/ruby/1.8/date.rb

DateTime is a subclass of Date which makes these methods (among others) public:

  • hour()
  • min()
  • sec()

[edit] Caveat: you may need to require certain date classes for certain Date/Time features

> ruby -rtime -e 'p $LOADED_FEATURES.grep(/date/); puts Time.parse("2007-01-01")'
["date/format.rb", "parsedate.rb"]
Mon Jan 01 00:00:00 -0800 2007

> ruby -rdate -e 'p $LOADED_FEATURES.grep(/date/); puts Date.parse("2007-01-01")'
["date/format.rb", "date.rb"]
2007-01-01

So "parsedate.rb" is needed in order to parse for Time, but not for Date. Odd.

[edit] Caveat: irb gives you an incomplete Date class by default

irb -> Date
    => Date

irb -> $LOADED_FEATURES.grep /date/
    => ["date/format.rb", "parsedate.rb"]

irb ->  Date::civil(2003, 4, 8)
NoMethodError: undefined method `civil' for Date:Class
        from (irb):4
irb -> require 'date'
    => true

irb -> $LOADED_FEATURES.grep /date/
    => ["date/format.rb", "parsedate.rb", "date.rb"]

irb ->  Date::civil(2003, 4, 8)
    => #<Date: 4905475/2,0,2299161>

Plain old ruby, however, doesn't give you any Date class at all by default...

> ruby -e 'Date'
-e:1: uninitialized constant Date (NameError)

My solution to this confusion was to add this line to my .irbrc:

require 'date'      # Since irb only gives you ["date/format.rb", "parsedate.rb"] by default!

[edit] How to increment by day or month

irb -> (Date.new(2006, 12, 14) + 1).to_s
    => "2006-12-15"

irb -> (Date.new(2006, 12, 14) >> 1).to_s
    => "2007-01-14"

[edit] What's the difference between Time and Datetime??

...

[edit] Having Date, Time, and Datetime classes but no easy way to convert between them

Ruby on Rails's ActiveSupport provides the much-needed Time.to_date() conversion...but that should be core Ruby!!

[edit] How do you instantiate a Date object with the current date/time? What's the equivalent of Time.now in the Date class?

Date.today

[edit] How do I get an ISO-8601 date?

> require 'date'
> Date.today.to_s
    => "2006-08-21"

> DateTime.now.to_s
    => "2006-08-21T13:08:34-0700"

> DateTime.now..to_s[0..18]
    => "2006-08-21T13:14:15"

# Or use strftime. This example is from ActiveRecord:
user.created_at.strftime("%Y-%m-%d %H:%M:%S")

[edit] How do I create a Time object from a Unix timestamp?

>> Time.at(1161200857)
=> Wed Oct 18 12:47:37 PDT 2006

[edit] Date: Iterators for days

# Print the days from 2006-11-01 through 2006-11-05
irb -> require 'date'

irb -> ((a=Date.new(2006, 11, 1)) .. a+4).each {|d| puts d.to_s}
2006-11-01
2006-11-02
2006-11-03
2006-11-04
2006-11-05

[edit] More examples

irb -> now = Time.now; "#{now.strftime("%a")}, #{now.strftime("%b")} #{now.day}, #{now.year}"
    => "Wed, Nov 1, 2006"
  def date_options(today)
    [
      "Not sure",
      (today + 1 .. today + 13).select { |date|
        Date::DAYNAMES[date.wday] != "Sunday"
      }.collect { |date|
        "#{date.strftime("%a, %b")} #{date.day}"
      }.collect { |option_string|
        [
          "#{option_string} - morning",
          "#{option_string} - afternoon"
        ]
      },
      "Other"
    ].flatten
  end

produces

["Not sure",
 "Thu, Nov 2 - morning",
 "Thu, Nov 2 - afternoon",
 "Fri, Nov 3 - morning",
 "Fri, Nov 3 - afternoon",
 "Sat, Nov 4 - morning",
 "Sat, Nov 4 - afternoon",
 "Mon, Nov 6 - morning",
 "Mon, Nov 6 - afternoon",
 "Tue, Nov 7 - morning",
 "Tue, Nov 7 - afternoon",
 "Wed, Nov 8 - morning",
 "Wed, Nov 8 - afternoon",
 "Thu, Nov 9 - morning",
 "Thu, Nov 9 - afternoon",
 "Fri, Nov 10 - morning",
 "Fri, Nov 10 - afternoon",
 "Sat, Nov 11 - morning",
 "Sat, Nov 11 - afternoon",
 "Mon, Nov 13 - morning",
 "Mon, Nov 13 - afternoon",
 "Tue, Nov 14 - morning",
 "Tue, Nov 14 - afternoon",
 "Other"]

[edit] [Libraries (category)]

See also Rails_plugins_and_libraries_/_Lower-level#.5BRuby-level.5D:_Dates_and_times

[edit] DateUtils

Documentation: RDoc


Project/Development: http://rubyforge.org/projects/dateutils/


Description: DateUtils provide some handy classes to deal with Date e.g. Week, Month, Year




Readiness: 4 - Beta


[edit] Chronic

Categories/Tags: [Natural language parsers (category)]
Homepage: http://chronic.rubyforge.org/
Documentation: http://chronic.rubyforge.org/
Source code: sudo gem install chronic



Description: Chronic is a natural language date/time parser written in pure Ruby.





http://chronic.rubyforge.org/

  Chronic.parse('tomorrow')
    #=> Mon Aug 28 12:00:00 PDT 2006

  Chronic.parse('monday', :context => :past)
    #=> Mon Aug 21 12:00:00 PDT 2006

  Chronic.parse('this tuesday 5:00')
    #=> Tue Aug 29 17:00:00 PDT 2006

  Chronic.parse('this tuesday 5:00', :ambiguous_time_range => :none)
    #=> Tue Aug 29 05:00:00 PDT 2006


[edit] Article metadata

Dates and times  edit   (Category  edit)


Facts about Ruby / Dates and timesRDF feed
Description [Oops! No type defined for attribute]
Personal tools