字符串
"2011-05-19 10:30:14"
To
Thu May 19 10:30:14 UTC 2011
如何将特定的字符串转换为此日期格式?
字符串
"2011-05-19 10:30:14"
To
Thu May 19 10:30:14 UTC 2011
require 'date'
date = DateTime.parse("2011-05-19 10:30:14")
formatted_date = date.strftime('%a %b %d %H:%M:%S %Z %Y')
有关日期格式化的更多信息,请参见strftime()。
"2011-05-19 10:30:14".to_time
@todaydate = "2011-05-19 10:30:14"
@todaytime.to_time.strftime('%a %b %d %H:%M:%S %Z %Y')
你会得到你想要的正确格式。你可以在Rails Console中检查它。
Loading development environment (Rails 3.0.4)
ruby-1.9.2-p136 :001 > todaytime = "2011-05-19 10:30:14"
=> "2011-05-19 10:30:14"
ruby-1.9.2-p136 :002 > todaytime
=> "2011-05-19 10:30:14"
ruby-1.9.2-p136 :003 > todaytime.to_time
=> 2011-05-19 10:30:14 UTC
ruby-1.9.2-p136 :008 > todaytime.to_time.strftime('%a %b %d %H:%M:%S %Z %Y')
=> "Thu May 19 10:30:14 UTC 2011"
尝试使用'date_format' gem来以不同的格式显示日期。
更多格式:
require 'date'
date = "01/07/2016 09:17AM"
DateTime.parse(date).strftime("%A, %b %d")
#=> Friday, Jul 01
DateTime.parse(date).strftime("%m/%d/%Y")
#=> 07/01/2016
DateTime.parse(date).strftime("%m-%e-%y %H:%M")
#=> 07- 1-16 09:17
DateTime.parse(date).strftime("%b %e")
#=> Jul 1
DateTime.parse(date).strftime("%l:%M %p")
#=> 9:17 AM
DateTime.parse(date).strftime("%B %Y")
#=> July 2016
DateTime.parse(date).strftime("%b %d, %Y")
#=> Jul 01, 2016
DateTime.parse(date).strftime("%a, %e %b %Y %H:%M:%S %z")
#=> Fri, 1 Jul 2016 09:17:00 +0200
DateTime.parse(date).strftime("%Y-%m-%dT%l:%M:%S%z")
#=> 2016-07-01T 9:17:00+0200
DateTime.parse(date).strftime("%I:%M:%S %p")
#=> 09:17:00 AM
DateTime.parse(date).strftime("%H:%M:%S")
#=> 09:17:00
DateTime.parse(date).strftime("%e %b %Y %H:%M:%S%p")
#=> 1 Jul 2016 09:17:00AM
DateTime.parse(date).strftime("%d.%m.%y")
#=> 01.07.16
DateTime.parse(date).strftime("%A, %d %b %Y %l:%M %p")
#=> Friday, 01 Jul 2016 9:17 AM
"2011-05-19 10:30:14".to_datetime.strftime('%a %b %d %H:%M:%S %Z %Y')
使用日期转换中的DATE_FORMAT
:
在你的初始化代码中:
DateTime::DATE_FORMATS[:my_date_format] = "%a %b %d %H:%M:%S %Z %Y"
在您的看法中:
date = DateTime.parse("2011-05-19 10:30:14")
date.to_formatted_s(:my_date_format)
date.to_s(:my_date_format)
<%= string_to_datetime("2011-05-19 10:30:14") %>
def string_to_datetime(string,format="%Y-%m-%d %H:%M:%S")
DateTime.strptime(string, format).to_time unless string.blank?
end
require 'active_support/core_ext/string'
来获取它。请参阅http://apidock.com/rails/String/to_time。 - Dipil