ruby 如何从 DateTime 值中删除区域?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9132337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I remove the zone from a DateTime value?
提问by Dagosi
I have this DateTime:
我有这个日期时间:
=> Fri, 03 Feb 2012 11:52:42 -0500
How can I remove the zone(-0500) in ruby? I just want something like this:
如何删除 ruby 中的区域(-0500)?我只想要这样的东西:
=> Fri, 03 Feb 2012 11:52:42
回答by Phrogz
Time always has a zone (it has no meaning without one). You can choose to ignore it when printing by using DateTime#strftime:
时间总是有一个区域(没有区域就没有意义)。您可以在打印时选择忽略它DateTime#strftime:
now = DateTime.now
puts now
#=> 2012-02-03T10:01:24-07:00
puts now.strftime('%a, %d %b %Y %H:%M:%S')
#=> Fri, 03 Feb 2012 10:01:24
See Time#strftimefor the arcane codes used to construct a particular format.
请参阅Time#strftime用于构建特定格式的神秘代码。
Alternatively, you may wish to convert your DateTime to UTCfor a more general representation.
或者,您可能希望将 DateTime 转换为 UTC以获得更一般的表示。
回答by xxjjnn
When all else fails
当一切都失败时
zoned_time = Time.now
unzoned_time = Time.new(zoned_time.year, zoned_time.month, zoned_time.day, zoned_time.hour, zoned_time.min, zoned_time.sec, "+00:00")
回答by PhilT
In addition to the accepted answer you can also add the same strftimeparameters to DATE_FORMATSa Rails hash allowing you to standardise output formats in your application.
除了接受的答案之外,您还可以将相同的strftime参数添加到DATE_FORMATSRails 哈希中,从而允许您在应用程序中标准化输出格式。
In config/initializers/datetime_formats.rb:
在config/initializers/datetime_formats.rb:
Time::DATE_FORMATS[:nozone] = '%a, %d %b %Y %H:%M:%S'
Then in your code you could do:
然后在您的代码中,您可以执行以下操作:
Time.zone.now.to_s(:nozone)
You could even make it the default:
您甚至可以将其设为默认值:
Time::DATE_FORMATS[:default] = '%a, %d %b %Y %H:%M:%S'
Time.zone.now.to_s
There is also a separate hash for dates:
还有一个单独的日期哈希:
Date::DATE_FORMATS[:default] = '%a, %d %b %Y'
This feature has been around for years but appears to be little known.
此功能已存在多年,但似乎鲜为人知。

