How do I create a Ruby date object from a string?

2020-02-17 06:02发布

How do I create a Ruby date object from the following string?

DD-MM-YYYY

标签: ruby date
7条回答
forever°为你锁心
2楼-- · 2020-02-17 06:30

I find this approach simpler since it avoid having to specify the date format for the parser:

date1 = Time.local(2012, 1, 20, 12, 0, 0).to_date

查看更多
男人必须洒脱
3楼-- · 2020-02-17 06:32

You can use Time#parse.

Time.parse("20-08-2010")
# => Fri Aug 20 00:00:00 +0200 2010

However, because Ruby could parse the date as "MM-DD-YYYY", the best way is to go with DateTime#strptime where you can specify the input format.

查看更多
▲ chillily
4楼-- · 2020-02-17 06:33
Date.parse('31-12-2010')

Alternatively Date#strptime(str, format).

查看更多
贪生不怕死
5楼-- · 2020-02-17 06:33

Like this You can get time Object from a string like this:

t = Time.parse "9:00 PM" 
 => 2013-12-24 21:00:00 +0530

t = Time.parse "12:00 AM"
 => 2013-12-24 00:00:00 +0530 

But Ruby parsing this as a Date!

So you can use the column as a string.

add_column :table_name, :from, :string, :limit => 8, :default => "00:00 AM", :null => false
add_column :table_name, :to, :string, :limit => 8, :default => "00:00 AM", :null => false 

And you can assign string object to the attribute,

r.from = "05:30 PM"
r.save

And parse the string for getting time object,

Time.zone.parse("02:00 PM")
查看更多
该账号已被封号
6楼-- · 2020-02-17 06:39

Not necessary for this particular string format, but best string to time parsing utility I know is Chronic which is available as a gem and works for about 99.9% of usecases for human formatted dates/times.

查看更多
ら.Afraid
7楼-- · 2020-02-17 06:48

If you have control over the format of the date in the string, then Date.parse works fine internationally with strings in YYYY-MM-DD (ISO 8601) format:

Date.parse('2019-11-20')
查看更多
登录 后发表回答