so... i need to take times from dates inside Array
so for example I have an array like this
a = [
Thu, 17 Mar 2022 10:00:00.000000000 KST 09:00,
Thu, 17 Mar 2022 10:00:00.000000000 KST 09:00,
Thu, 17 Mar 2022 14:00:00.000000000 KST 09:00,
Thu, 17 Mar 2022 14:00:00.000000000 KST 09:00,
Thu, 17 Mar 2022 17:00:00.000000000 KST 09:00]
and wanted to have result of
a = ["10:00", "10:00", "14:00", "14:00", "17:00"]
So i was trying this
can_choose =[];
a.each_with_index do |time| strftime("%H:%M")
can_choose <<|time|
but doesn't works at all...
where should I have to fix??
CodePudding user response:
You can also extract the year, month, day the same way https://ruby-doc.org/stdlib-3.1.1/libdoc/date/rdoc/Date.html
a = [
'Thu, 17 Mar 2022 10:00:00.000000000 KST 09:00',
'Thu, 17 Mar 2022 10:00:00.000000000 KST 09:00',
'Thu, 17 Mar 2022 14:00:00.000000000 KST 09:00',
'Thu, 17 Mar 2022 14:00:00.000000000 KST 09:00',
'Thu, 17 Mar 2022 17:00:00.000000000 KST 09:00']
can_choose =[]
a.map do |time|
t = DateTime.parse(time)
can_choose << t.strftime("%k:%M")
end
p can_choose
=> ["10:00", "10:00", "14:00", "14:00", "17:00"]
CodePudding user response:
Ruby is all about message passing. The syntax to send a message is:
receiver.message(argument)
strftime
is such message, but it needs a proper receiver. So if you have some Time
instance, e.g.:
time = Time.parse('2022-03-17 10:00:00 0900')
you'd write:
time.strftime('%H:%M') #=> "10:00"
with time
being the receiver, strftime
being the message and '%H:%M'
being the argument.
You can use the above code in an each
loop like this:
can_choose = []
a.each do |time|
can_choose << time.strftime('%H:%M')
end
Or you could use map
to convert your array to another array:
can_choose = a.map { |time| time.strftime('%H:%M') }
The curly braces here { ... }
are equivalent to the do ... end
block above.
CodePudding user response:
I would simple go with:
can_choose = a.map { |datetime| datetime.strftime('%H:%M') }
CodePudding user response:
If you need only hours and minutes in 24h format, just use %R
directive with Time#strftime
or DateTime#strftime
can_choose = a.map { |time| time.strftime('%R') }