Rails 中的日期时间比较失败 [英] DateTime comparison fails in Rails

查看:59
本文介绍了Rails 中的日期时间比较失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,比较总是失败,请从 Rails 控制台查看:

For some reason, the comparison always fail, please check this out from Rails console :

irb(main):021:0> @game.game_date.class
=> ActiveSupport::TimeWithZone
irb(main):026:0> @game.game_date
=> Tue, 19 Feb 2013 23:15:00 UTC +00:00
irb(main):022:0> @game.game_date.to_datetime
=> Tue, 19 Feb 2013 23:15:00 +0000
irb(main):019:0> DateTime.now
=> Tue, 19 Feb 2013 23:48:38 +0330
irb(main):020:0> @game.game_date.to_datetime > DateTime.now
=> true

怎么比较总是错误的?我也试过这个:

How come that the comparison is always wrong? I tried this as well:

@game.game_date.to_time > Time.now.to_tim

结果也为真,但很明显自 23:48 > 23:15:00 以来它应该是假的.

The result was true as well , while it's obvious that it is supposed to be false since 23:48 > 23:15:00.

请注意,我在 ubuntu 和 Rails 3.1 下使用 ruby​​ ruby​​ 1.9.3p0

Please note that i'm using ruby ruby 1.9.3p0 under ubuntu and Rails 3.1

任何帮助将不胜感激

推荐答案

您的时区有问题:

irb(main):022:0> @game.game_date.to_datetime
=> Tue, 19 Feb 2013 23:15:00 +0000
irb(main):019:0> DateTime.now
=> Tue, 19 Feb 2013 23:48:38 +0330

你看,你的 game_date 属性有一个 +0000 时区,而 DateTime.now 有一个 +0330

You see, your game_date attribute has a +0000 TimeZone, when DateTime.now has a +0330

试试这个:

@game.game_date.to_datetime > Time.zone.now

这篇关于Rails 中的日期时间比较失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆