Ruby-on-rails 如何在 Rails 中以“mm/dd/yyyy”格式显示当前日期

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

How to display the current date in "mm/dd/yyyy" format in Rails

ruby-on-railsrubydate

提问by akshay1188

In my view I want to display the current date in "mm/dd/yyyy" format.

在我看来,我想以“mm/dd/yyyy”格式显示当前日期。

回答by Jeff

<%= Time.now.strftime("%m/%d/%Y") %>

回答by jerhinesmith

You could simply do (substitute in Timefor DateTimeif using straight Ruby -- i.e. no Rails):

你可以简单地做(替代在TimeDateTime是否采用直板红宝石-即没有Rails的):

DateTime.now.strftime('%m/%d/%Y')

If you're using that format a lot, you might want to create a date_time_formatsinitializer in your RAILS_ROOT/config/initializersfolder (assuming Rails 2), something like this:

如果你经常使用这种格式,你可能想date_time_formats在你的RAILS_ROOT/config/initializers文件夹中创建一个初始化程序(假设是 Rails 2),如下所示:

# File: date_time_formats.rb
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
  :human => "%m/%d/%Y"
)

Which will then let you use the more friendly version of DateTime.now.to_s(:human)in your code.

这将让您DateTime.now.to_s(:human)在代码中使用更友好的版本。

回答by Budgie

I think you can use .strftime:

我认为你可以使用.strftime

t = Time.now()
t.strftime("The date is %m/%d/%y")

This should give "The date is 09/09/10". See herefor a great list of the format codes for .strftime.

这应该给"The date is 09/09/10". 请参阅此处以获取.strftime.

回答by Spyros

If you don't need the full year you could try Time.now.strftime('%D')

如果你不需要全年,你可以尝试 Time.now.strftime('%D')