How can I remove the zone from a DateTime value?

后端 未结 3 807
渐次进展
渐次进展 2021-01-03 18:22

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:

3条回答
  •  臣服心动
    2021-01-03 18:31

    In addition to the accepted answer you can also add the same strftime parameters to DATE_FORMATS a Rails hash allowing you to standardise output formats in your application.

    In 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.

提交回复
热议问题