Why is Ruby's Date class automatically loaded but DateTime is not?
Being a little more curious, I tried:
$ ruby -e 'puts DateTime.class'
-e:1:in `<main>': uninitialized constant Object::DateTime (NameError)
[~, kamilski81@mac]
$ ruby -e 'puts Date.class'
-e:1:in `<main>': uninitialized constant Object::Date (NameError)
$ ruby -e 'puts Time.class'
Class
So it makes me think that it's an irb issue that automatically loads 'date'.
Why can I use the Date class without requiring 'date'?
Rubygems (which is required by default) defines a empty, non-functioning Date
class in versions earlier than 2.4.0 (Rubygems version, not Ruby). This has been fixed recently (also see the Ruby bug report). The version of Rubygems with the fix will likely be included in Ruby 2.2.
Are the Date, Time, and DateTime classes necessary?
DateTime
is a subclass of Date
, so whatever you can do with Date
can be done with DateTime
. But as tadman and steenslag point out, DateTime
is slower. See steenslag's answer for how much slower it is.
With respect to DateTime
vs, Time
, I found something here:
Time is a wrapper around Unix-Epoch.
Date (and DateTime) use rational and a "day zero" for storage. So Time is faster but the upper and lower bounds are tied to epoch time (which for 32bit epoch times is something around 1970-2040...while Date (and DateTime) have an almost infinite range but are terribly slow.
In short, DateTime
is an all around superstar, and should be preferred in general, but if you want to optimize to the last bit, using Time
can improve performance.
Why does Date exist in Ruby before it is required?
I believe that date
doesn't come from irb
, but from rubygems
, specifically the file where Gem::Specification
is defined:
class Date; end # for ruby_code if date.rb wasn't required
I believe they needed any Date
class defined so that the interpreter doesn't complain further down in the Specification
class.
How to avoid from storing date objects in array in Ruby?
dates.map { |e| Date.parse(e).strftime('%Y-%m-%d') }
#=> ["1232-10-20", "2019-06-06", "2017-08-23", "2015-01-09"]
Change the template '%Y-%m-%d'
according to your needs, see this for reference: Date#strftime.
Picking up the wise suggestion from Cary Swoveland.
Instead of Date.parse(e)
you can use Date.strptime(e, '%dth %b %Y')
, which works more or less the reverse of strftime. See Date#strptime. It follows a template ('%dth %b %Y'
) to interpret the original string as a date. Adding th
to the template after %d
(day), it converts properly the current format to a date object:
Date.strptime("20th OCT 1232", '%dth %b %Y') #=> #<Date: 1232-10-20 ((2171339j,0s,0n),+0s,2299161j)>
But, what if the date is '1st OCT 2018'
or '23rd OCT 2018'
? The template does not match, because it expects to find th
and not st
or rd
.
To be ordinal suffix agnostic, comes in hand the method String#sub:
"20th OCT 1232".sub(/(?<=\d)\p{Alpha}+/, '') #=> "20 OCT 1232"
So, mixing all together, the best solution to be safe should be:
dates.map { |e| Date.strptime(e.sub(/(?<=\d)\p{Alpha}+/, ''), '%d %b %Y').strftime('%Y-%m-%d') }
Mongoid - Getting Date instead of Time when serializing DateTime field in JSON API response
Issue seems to be in your code:
class GroceryItem
include Mongoid::Document
field :name, type: String
field :expiry, type: Date
end
Here, expiry has type of Date, so it is expected to return a Date without time component. I think using the appropriate type will solve your problem.
Rails 'config.time_zone' doesn't apply to datetime data loaded into a text_field. Fix?
As I said in the question, the main problem I had was getting ActiveRecord to apply the existing 'config.time_zone' setting to text_fields.
It turns out that there's a very simple and future-proof way to make that happen: just explicitly add a :value and pull the exact same data--no extra/new methods to call! In my case, that meant:
<%= f.text_field :time_start, :value => f.object.time_start, :class => "datetimefield" %>
This was an intermediary step to another potential solution I was going to try, and I was surprised to find that it worked all on its own (again, working with the 'config.time_zone' I'd already set in 'config/application.rb').
I've tested it, and it applies the proper DST offset when applicable as well (just as one would expect, since 'config.time_zone' is set).
Related Topics
Pg Error Could Not Connect to Server: Connection Refused Is the Server Running on Port 5432
How to Make a Gemset in Rvm the Default
Are There Better Ways to Prevent 'Yield' When No Block Is Passed In
Deleting a Hash from Array of Hashes in Ruby
Can't Convert Symbol into String
Nokogiri To_Xml Without Carriage Returns
Convert Array to Hash While Preserving Array Index Values in Ruby
How to Assign Multiple Values to a Hash Key
How to Get a List of Files That Have Been 'Required' in Ruby
Weird Rails Error "Permission Denied: Bin/Rails" for Old Rails Apps
Differencebetween #Encode and #Force_Encoding in Ruby
Differencebetween "Be_True" and "Be True" in Rspec
Ruby: Write Escaped String to Yaml