0

I am running into an odd issue when I store a DateTime field using Mongoid into MongoDB. On the surface of things from the Ruby side, things look okay:

irb(main):002:0> dt=DateTime.strptime("12/02/13 13:25:21", "%m/%d/%Y %H:%M:%S")
=> #<DateTime: 0013-12-02T13:25:21+00:00 ((1726142j,48321s,0n),+0s,2299161j)>


irb(main):003:0> dt.day
=> 2
irb(main):004:0> dt.month
=> 12
irb(main):005:0> dt.year
=> 13
irb(main):006:0> dt.hour
=> 13
irb(main):007:0> dt.minute
=> 25
irb(main):008:0> dt.second
=> 21

Now when I store this in MongoDB using Mongoid, it gets stored like the following:

class Foo
  include Mongoid::Document
  include Mongoid::Timestamps

  field :datetime, type: DateTime

  def set_stuff_up
    self.datetime = DateTime.strptime("12/02/13 13:25:21", "%m/%d/%Y %H:%M:%S")
  end
end

When I retrieve this from the database, this is where the issue occurs:

> db.foos.findOne().datetime
ISODate("0013-11-30T13:25:21Z")
> db.foos.findOne().datetime.getMonth()
10
> db.foos.findOne().datetime.getDay()
6
> db.foos.findOne().datetime.getYear()
-1887

Results are similarly skewed on the Ruby end of things. Me using findOne() to retrieve the document here is fine by the way, as there is only one document in the collection:

> db.foos.find().size()
1
4

1 回答 1

1

您对该日期格式使用了错误的格式字符串。A%Y是四位数年份,%y是两位数年份。来自精美手册

%Y - Year with century (can be negative, 4 digits at least)
        -0001, 0000, 1995, 2009, 14292, etc.
...
%y - year % 100 (00..99)

您甚至可以在控制台中看到年份不正确:

=> #<DateTime: 0013-12-02T13:25:21+00:00 ((1726142j,48321s,0n),+0s,2299161j)>

dt.year价值:

irb(main):005:0> dt.year
=> 13

0013 和 2013 不太一样。

你想说:

self.datetime = DateTime.strptime("12/02/13 13:25:21", "%m/%d/%y %H:%M:%S")
# ------------------------------------------------------------^^
于 2013-08-29T23:24:46.307 回答