将字符串转换为特定的日期时间格式?

67

字符串

"2011-05-19 10:30:14"

To

Thu May 19 10:30:14 UTC 2011

如何将特定的字符串转换为此日期格式?
7个回答

130
require 'date'

date = DateTime.parse("2011-05-19 10:30:14")
formatted_date = date.strftime('%a %b %d %H:%M:%S %Z %Y')

有关日期格式化的更多信息,请参见strftime()


35

"2011-05-19 10:30:14".to_time


我遇到了NoMethodError错误...你正在加载哪些模块? - mrek
3
这个方法是在Rails中定义的,更具体地说,是在activesupport的字符串扩展中定义的。你可以使用require 'active_support/core_ext/string'来获取它。请参阅http://apidock.com/rails/String/to_time。 - Dipil
虽然这可能回答了问题,但请不要发布仅包含代码的答案。 - Daniel W.

17
无需添加任何内容,只需在分配日期的变量末尾添加此代码。例如:
   @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来以不同的格式显示日期。


11

更多格式:

 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

5
这是另一个有用的代码:

"2011-05-19 10:30:14".to_datetime.strftime('%a %b %d %H:%M:%S %Z %Y')

3

使用日期转换中的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) 

3
  <%= 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接