I have no clue what I am doing wrong. I have followed numerous examples and I can't get this to work out. I have a string with the following time:
text_t = 1:00 PM ET
I try to convert it to a DateTime object so I can easily add 30 minutes to the value with the following code:
text_next = DateTime.strptime(text_t, '%I:%M %p %Z')
puts text_next
text_next = text_next + 1800
puts text_next
but my output looks like the following:
1:00 PM ET
2013-07-02T13:00:00+00:00
2018-06-06T13:00:00+00:00
I need to increment the time by 30 minutes and then convert is back to a string in the same format it came in. I could make a function that manipulates the string to be 30 minutes ahead but I feel like that's a lot of work and there must be something that gives this functionality.
You are adding 1800 days to your date.
I tried this:
text_next = DateTime.strptime(text_t, '%I:%M %p %Z')
puts text_next
text_next = text_next + Rational(30, 1440)
puts text_next
1440 is the amount of minutes in a day.
what about? as long as you're using activesupport of course
text_t = "1:00 PM ET"
text_next = DateTime.strptime(text_t, '%I:%M %p %Z')
text_next = text_next + 30.minutes
Here is the approach I will follow:
require 'date'
text_t = '2:12:03 PM ET'
dt = DateTime.parse(text_t, '%I:%M %p %Z')
# => #<DateTime: 2013-07-03T14:12:03+00:00 ((2456477j,51123s,0n),+0s,2299161j)>
dt.to_s
# => "2013-07-03T14:12:03+00:00" # !> invalid offset is ignored
dh = Date._strptime(dt.to_s,'%Y-%m-%dT%H:%M:%S%z')
# => {:year=>2013,
# :mon=>7,
# :mday=>3,
# :hour=>14,
# :min=>12,
# :sec=>3,
# :zone=>"+00:00",
# :offset=>0}
dh[:hour] += 30 # => 44
dh
# => {:year=>2013,
# :mon=>7,
# :mday=>3,
# :hour=>44,
# :min=>12,
# :sec=>3,
# :zone=>"+00:00",
# :offset=>0}
dh.values[0..-2].join(" ")
# => "2013 7 3 44 12 3 +00:00"
DateTime.ordinal(*dh.values[0..-3])
# => #<DateTime: 2013-01-07T03:44:12+00:00 ((2456300j,13452s,0n),+0s,2299161j)>
Now Its your choice how you want to see your Date
object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.