Ruby-on-rails 更改 Rails 4 中的默认日期和时间格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17870762/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:23:38  来源:igfitidea点击:

Changing the default date and time format in Rails 4

ruby-on-railsdatetimeruby-on-rails-4internationalization

提问by smile2day

I was looking for a way to change the default date format in Rails 4.

我一直在寻找一种方法来更改 Rails 4 中的默认日期格式。

回答by smile2day

Found a nice approach through the Rails Internationalization (I18n) API

通过Rails Internationalization (I18n) API找到了一个很好的方法

Data and time formats can be 'translated' by adding the format to the i18n configuration.

可以通过将格式添加到 i18n 配置来“转换”数据和时间格式。

config/locales/en.yml

配置/语言环境/en.yml

en:
  date:
    formats:
      default: "%d/%m/%Y"
  time:
    formats:
      default: "%d/%m/%Y %H:%M"

Note: remember to not have tabs for the indent, like I did first time :)

注意:记住不要有缩进的制表符,就像我第一次那样:)



As mentioned by NoelProf in the comments

正如 NoelProf 在评论中提到的

To use i18n conversion don't forget the l (lower case L) before your date in views! For example: <%= l your_date %>

要使用 i18n 转换,请不要忘记查看日期之前的 l(小写 L)!例如:<%= l your_date %>

You are invited to comment if you found other ways working well.

如果您发现其他方法行之有效,欢迎您发表评论。

回答by 732

Add this

添加这个

# Date
Date::DATE_FORMATS[:default] = "%d/%m/%Y" 

# Time
Time::DATE_FORMATS[:default] = "%d/%m/%Y %H:%M" 

to config/initializers/date_time.rb

到 config/initializers/date_time.rb

Then restart the server.

然后重新启动服务器

回答by Markus Andreas

If you use i18n conversion don't forget the lmethod before your dates in views!

如果您使用 i18n 转换,请不要忘记l视图中日期之前的方法!

<%= l your_date %>