Ruby字符串到日期转换 [英] Ruby String to Date Conversion
本文介绍了Ruby字符串到日期转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Tue,2010年8月10日01:20:19 -0400(EDT)
的字符串转换为日期对象。 有没有办法我可以做到这一点。
这是我以前看过和尝试的,没有运气:
-
Date.strptime(更新,%a,%d%m%Y%H:%M:%S%Z )
- 慢性解析器
- Ruby:将字符串转换为日期
- 使用Ruby解析文本的日期
请帮我解决这个问题。
解决方案
Date.parse
方法有什么问题?
str =Tue,2010年8月10日01:20:19 -0400(EDT)
date = .parse str
=> #< Date:4910837 / 2,0,2299161>
放置日期
2010-08-10
似乎有效。 / p>
这里唯一的问题是时区。如果你想要UTC时区的日期,那么最好使用 Time
对象,假设我们有字符串:
str =Tue,2010年8月10日01:20:19 +0400
放置Date.parse str
2010-08-10
puts日期.parse(Time.parse(str).utc.to_s)
2010-08-09
我找不到更简单的方法来将 Time
转换为 Date
。
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.
Is there anyway i could do this.
Here is what I've looked and tried at the following with no luck:
Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")
- Chronic Parser
- Ruby: convert string to date
- Parsing date from text using Ruby
Please help me out with this.
解决方案
What is wrong with Date.parse
method?
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 Time
object, suppose we have string:
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 Time
to Date
.
这篇关于Ruby字符串到日期转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文