Ruby 字符串到日期的转换

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

Ruby String to Date Conversion

ruby-on-railsrubydatetimedate

提问by dkris

I am faced with an issue in Ruby on Rails. I am looking to convert a string of format Tue, 10 Aug 2010 01:20:19 -0400 (EDT)to a date object.

我在 Ruby on Rails 中遇到了一个问题。我正在寻找将格式字符串转换Tue, 10 Aug 2010 01:20:19 -0400 (EDT)为日期对象。

Is there anyway i could do this.

无论如何我可以做到这一点。

Here is what I've looked and tried at the following with no luck:

这是我在没有运气的情况下查看和尝试的内容:

  1. Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")
  2. Chronic Parser
  3. Ruby: convert string to date
  4. Parsing date from text using Ruby
  1. Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")
  2. 慢性解析器
  3. Ruby:将字符串转换为日期
  4. 使用 Ruby 从文本中解析日期

Please help me out with this.

这个你能帮我吗。

回答by klew

What is wrong with Date.parsemethod?

Date.parse方法有什么问题?

str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
date = Date.parse str
=> #<Date: 4910837/2,0,2299161>
puts date
2010-08-10

It seems to work.

它似乎工作。

The only problem here is time zone. If you want date in UTC time zone, then it is better to use Timeobject, suppose we have string:

这里唯一的问题是时区。如果你想要UTC时区的日期,那么最好使用Time对象,假设我们有字符串:

str = "Tue, 10 Aug 2010 01:20:19 +0400"
puts Date.parse str
2010-08-10
puts Date.parse(Time.parse(str).utc.to_s)
2010-08-09

I couldn't find simpler method to convert Timeto Date.

我找不到更简单的方法来转换TimeDate.

回答by steenslag

Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")

Should be:

应该:

Date.strptime(updated, '%a, %d %b %Y %H:%M:%S %Z')

回答by Wadester

str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
str.to_date
=> Tue, 10 Aug 2010

回答by Sergey Chechaev

You can try https://rubygems.org/gems/dates_from_string:

您可以尝试https://rubygems.org/gems/dates_from_string

Find date in structure:

在结构中查找日期:

text = "get car from repair 2015-02-02 23:00:10"
dates_from_string = DatesFromString.new
dates_from_string.find_date(text)

=> ["2015-02-02 23:00:10"]