Ōkami X Oukarin
Ōkami X Oukarin

Reputation: 435

Rails - Convert string to time

I'm trying to parse these string into time: "3 on Jun 20", "Jun 20 at 3", "Jun 20 at 300".

Using DateTime.parse didnt parse "3", "300" into "3:00 AM", it just returns Wed, 20 Jun 2018 00:00:00 +0000.

Anyone has any idea to parse these integer into time?

Upvotes: 0

Views: 228

Answers (3)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

Just out of curiosity, trying to reinvent chronic in 4 LOCs :)

["3 on Jun 20", "Jun 20 at 3", "Jun 20 at 300"].map do |dt|
  d, t = dt.split(/\s+at\s+/i)
  t, d = dt.split(/\s+on\s+/i) unless t
  return [dt] unless t && d

  t = t[0..-3] + (t[-2..-1] ? ":" << t[-2..-1] : t[/.{,2}\z/] + ":00")
  [d, t] # [["Jun 20", "3:00"], ["Jun 20", "3:00"], ["Jun 20", "3:00"]]
end.map { |dt| DateTime.parse dt.join ' ' }

Upvotes: 4

Stefan
Stefan

Reputation: 114248

There's Chronic, a "natural language date/time parser":

require 'chronic'

Chronic.parse('3 on Jun 20')    #=> 2018-06-20 15:00:00 +0200
Chronic.parse('Jun 20 at 3')    #=> 2018-06-20 15:00:00 +0200
Chronic.parse('Jun 20 at 300')  #=> 2018-06-20 15:00:00 +0200

Upvotes: 6

Alexis
Alexis

Reputation: 364

Use strptime to parse a custom format:

DateTime.strptime("3 on Jun 20", "%H on %b %d")

https://ruby-doc.org/stdlib-2.5.0/libdoc/date/rdoc/DateTime.html#method-c-strptime

Upvotes: 1

Related Questions