Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #5747 (closed defect: fixed)

Opened 2 years ago

Last modified 2 years ago

[PATCH] time information lost when calling to_time on a DateTime

Reported by: jon.evans@pobox.com Assigned to: David
Priority: normal Milestone:
Component: ActiveSupport Version:
Severity: normal Keywords:
Cc: cch1

Description

core_ext adds a to_time method to Date, which constructs a new Time object from the Date's year, month and day. DateTime extends Date, and therefore also inherits the to_time method. Unfortunately the hour, minute and second aren't passed to the Time constructor even though they are available. The patch fixes this by checking if self responds to :hour. If it does, it is assumed to also respond to :min and :sec, and a Time object is returned containing all of that info. If it doesn't respond to :hour the code is the same as before the patch.

Without the patch, distance_of_time_in_words etc. is also broken as it calls to_time on the date parameter, which loses the time information. e.g. if I use time_ago_in_words(DateTime.now) (it is currently 15:04 BST) it will return "about 15 hours" rather than the expected "less than a minute".

Before patch:

>> d = DateTime.now
=> #<DateTime: 212021720810911099/86400000000,1/24,2299161>
>> d.to_time
=> Mon Aug 07 00:00:00 BST 2006
>> d.to_s
=> "2006-08-07T15:26:50+0100"

After patch:

>> d = DateTime.now
=> #<DateTime: 42404344549457039/17280000000,1/24,2299161>
>> d.to_time
=> Mon Aug 07 15:59:07 BST 2006
>> d.to_s
=> "2006-08-07T15:59:07+0100"

Attachments

date_conversions.diff (1.3 kB) - added by jon.evans@pobox.com on 08/07/06 15:15:41.
patch, with test case.

Change History

08/07/06 15:15:41 changed by jon.evans@pobox.com

  • attachment date_conversions.diff added.

patch, with test case.

08/07/06 22:07:39 changed by bitsweat

  • status changed from new to closed.
  • resolution set to fixed.

(In [4718]) DateTime#to_time gives hour/minute/second resolution. Closes #5747.

09/25/06 02:16:25 changed by cch1

  • cc set to cch1.