如何从字符串创建 Ruby 日期对象?

如何从以下字符串创建 Ruby 日期对象?

DD-MM-YYYY
80314 次浏览

你可以使用 时间解析

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.

Date.parse('31-12-2010')

或者 Date#strptime(str, format)

因为在美国他们把日期倒过来,所以重要的是不要简单地使用 Date.parse(),因为你会发现9/11/2001在美国可以是2001年9月11日,在世界其他地方是2001年11月9日。为了完全明确,请使用 Date::strptime(your_date_string,"%d-%m-%Y")正确地解析格式为 dd-mm-yyyy的日期字符串。

为了确保万无一失,试试这个:

>irb
>> require 'date'
=> true
>> testdate = '11-09-2001'
=> "11-09-2001"
>> converted = Date::strptime(testdate, "%d-%m-%Y")
=> #<Date: 4918207/2,0,2299161>
>> converted.mday
=> 11
>> converted.month
=> 9
>> converted.year
=> 2001

有关其他 strptime格式,请参见 http://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html

此外,如果我的网站要处理任何日期,我总是确保我的基准时区设置为 :utc,并在客户端使用 Javascript显示本地时间。

你可以从这样的字符串中得到时间对象:

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

但是 Ruby 把这个解析为 Date!

因此可以将该列用作字符串。

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")

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

我发现这种方法更简单,因为它避免了为解析器指定日期格式:

Date1 = Time.local (2012,1,20,12,0,0) . to _ date

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')