Ruby字符串到日期转换 [英] Ruby String to Date Conversion

查看:228
本文介绍了Ruby字符串到日期转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Ruby on Rails面临一个问题。我正在寻找一种格式为 Tue,2010年8月10日01:20:19 -0400(EDT)的字符串转换为日期对象。



有没有办法我可以做到这一点。



这是我以前看过和尝试的,没有运气:


  1. Date.strptime(更新,%a,%d%m%Y%H:%M:%S%Z )

  2. 慢性解析器

  3. Ruby:将字符串转换为日期

  4. 使用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:

  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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆