更改默认的 Ruby 时间格式 [英] Change default Ruby Time format

查看:37
本文介绍了更改默认的 Ruby 时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直不得不将.strftime("%H:%M")"附加到我的 Rails 项目中显示时间的任何内容.我有每个 Concert 对象的开始时间和结束时间,因此每当我想显示这些时间时,我都必须附加.strftime("%H:%M")".

请注意,我不是要求更改日期格式.日期看起来很好(如 MM/DD/YYYY).

解决这个问题的最佳方法是什么?有没有办法设置默认时间格式?

(我很确定这只是 Ruby 的事情,但我是新手,所以我不确定.)

解决方案

既然您使用的是 Rails,请充分利用 I18n 支持:http://guides.rubyonrails.org/i18n.html#adding-date-time-formats

# config/locales/en.ymlzh:时间:格式:默认值:%H:%M"

然后当您调用 I18n.l Time.now<%= l Time.now %> 时,它会自动使用该格式.>

I keep having to append ".strftime("%H:%M")" to anything that is displaying a time in my Rails project. I have a start time and an end time for each Concert object, so I have to append ".strftime("%H:%M")" whenever I wanna display those times.

Note that I'm not asking to change the date format. The date looks fine as it is (as MM/DD/YYYY).

What's the best way to get around this? Is there a way to set the default time format?

(I'm pretty sure this is only a Ruby thing, but I'm a newbie, so I'm not sure.)

解决方案

Since you're using Rails, take advantage of the I18n support: http://guides.rubyonrails.org/i18n.html#adding-date-time-formats

# config/locales/en.yml
en:
  time:
    formats:
      default: "%H:%M"

Then when you call I18n.l Time.now or <%= l Time.now %>, it'll use that format automatically.

这篇关于更改默认的 Ruby 时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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